且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用理解来创建Python字典

更新时间:2023-11-20 18:39:10

为什么错了:您的列表理解是嵌套的.实际上是这样的:

Why it's wrong: Your list comprehension is nested. It's effectively something like this:

d = {}
for x in map(chr, range(65, 91)):
    for y in range(1,27):
        d[x] = y

如您所见,这不是您想要的.将y设置为1,然后遍历字母,将所有字母设置为1,即{'A':1, 'B':1, 'C':1, ...}.然后,它再次针对2,3,4进行处理,一直到26.由于这是命令,因此以后的设置会覆盖以前的设置,然后您会看到结果.

As you can see, this isn't what you want. What it does is set y to 1, then walk through the alphabet, setting all letters to 1 i.e. {'A':1, 'B':1, 'C':1, ...}. Then it does it again for 2,3,4, all the way to 26. Since it's a dict, later settings overwrite earlier settings, and you see your result.

这里有几个选项,但是总的来说,遍历多个伴随列表的解决方案是一种更像这样的模式:

There are several options here, but in general, the solution to iterate over multiple companion lists is a pattern more like this:

[some_expr(a,b,c) for a,b,c in zip((a,list,of,values), (b, list, of, values), (c, list, of values))]

zip从每个子列表中提取一个值,并在每次迭代时将其放入一个元组.换句话说,它将每个4项的3个列表转换为每个3项的4个列表(在上面).在您的示例中,当您需要26对时,您有2个列表,共26个项目. zip会帮您做到这一点.

The zip pulls one value from each of the sublists and makes it into a tuple for each iteration. In other words, it converts 3 lists of 4 items each, into 4 lists of 3 items each (in the above). In your example, you have 2 lists of 26 items, when you want 26 pairs; zip will do that for you.