使用理解来创建Python字典 [英] Creating a Python dictionary using a comprehension

查看:60
本文介绍了使用理解来创建Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python 2.7.3中创建具有以下值的python字典:

I am trying to create a python dictionary with the following values in python 2.7.3:

'A':1
'B':2
'C':3
  .
  .
  .
  .
'Z':26

使用以下任一行:

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

theDict = {x:y for x in map(chr,range(65,91)) for y in list(range(1,27))}

在两种情况下,我都得到以下结果:

In both cases, I get the following result:

'A':26
'B':26
'C':26
  .
  .
  .
  .
'Z':26

我不明白第二个为什么不生成数字1-26.也许是,但是如果是这样,我不明白为什么我每个键的价值只能得到26.如果我不创建字典(即仅用x或y更改x:y),则x =大写字母,y = 1-26.

I don't understand why the second for is not generating the numbers 1-26. Maybe it is, but if so, I don't understand why I am only getting 26 for the value of each key. If I don't create a dictionary (i.e. change x:y with just x or y), x = capital letters and y = 1-26.

有人可以解释我在做什么错,并提出一种可能的方法来获得我想要的结果.

Can someone explain what I am doing wrong and suggest a possible approach to get the result that I want.

推荐答案

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

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.

这篇关于使用理解来创建Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆