[英]Python nested dict comprehension
Can someone explain how to do nested dict comprehensions? 有人可以解释如何做嵌套的字典理解吗?
>> j = dict(((x+y,0) for x in 'cd') for y in 'ab')
>> {('ca', 0): ('da', 0), ('cb', 0): ('db', 0)}
I would have liked: 我本来希望:
>> j
>> {'ca':0, 'cb':0, 'da':0, 'db':0}
Thanks! 谢谢!
dict((x+y,0) for x in 'cd' for y in 'ab')
You can simplify this to a single loop by using the cartesian product from itertools 您可以使用itertools中的笛卡尔积将其简化为单循环
>>> from itertools import product
>>> j=dict((x+y,0) for x,y in product('cd','ab'))
>>> j
{'cb': 0, 'ca': 0, 'db': 0, 'da': 0}
>>>
dict((x+2*y, 0) for x in range(1,4,2) for y in range(15, 18, 2))
顺便说一句,我们称之为dict理解就像下面这样只有Python2.7 +才能提供:
{x+2*y:0 for x in range(1,4,2) for y in range(15, 18, 2)}
The extra parentheses in the question introduce another generator expression that yields 2 generators each yielding 2 tuples. 问题中的额外括号引入了另一个生成器表达式,它产生2个生成器,每个生成器产生2个元组。 The list comprehension below shows exactly what is happening. 下面的列表理解准确地显示了正在发生的事情。
>>> [w for w in (((x+y,0) for x in 'cd') for y in 'ab')]
[<generator object <genexpr> at 0x1ca5d70>, <generator object <genexpr> at 0x1ca5b90>]
A list comprehension instead of the generator expression shows what the generators above contain 列表理解而不是生成器表达式显示上面的生成器包含的内容
>>> [w for w in ([(x+y,0) for x in 'cd'] for y in 'ab')]
[[('ca', 0), ('da', 0)], [('cb', 0), ('db', 0)]]
And that is why you were getting two key-value of pairs of tuples. 这就是为什么你得到两对元组的关键值。
Why mouad's answer works 为什么穆阿德的回答有效
>>> [w for w in ((x+y,0) for x in 'cd' for y in 'ab')]
[('ca', 0), ('cb', 0), ('da', 0), ('db', 0)]
In Python 2.7 and 3.0 and above, you can use dict comprehensions 在Python 2.7和3.0及更高版本中,您可以使用dict理解
>>> j = {x+y:0 for x in 'cd' for y in 'ab'}
>>> j
{'cb': 0, 'ca': 0, 'db': 0, 'da': 0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.