有人能解释一下如何进行嵌套字典推导吗?
>> 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}
谢谢!
有人能解释一下如何进行嵌套字典推导吗?
>> 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}
谢谢!
dict((x+y,0) for x in 'cd' for y in 'ab')
>>> 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))
顺便提一下,我们所谓的字典推导式是类似于以下代码的形式,只在Python2.7及以上版本中可用:
{x+2*y:0 for x in range(1,4,2) for y in range(15, 18, 2)}
>>> [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>]
>>> [w for w in ([(x+y,0) for x in 'cd'] for y in 'ab')]
[[('ca', 0), ('da', 0)], [('cb', 0), ('db', 0)]]
这就是为什么你会得到两个元组的键值对。
为什么Mouad的答案有效
>>> [w for w in ((x+y,0) for x in 'cd' for y in 'ab')]
[('ca', 0), ('cb', 0), ('da', 0), ('db', 0)]
>>> j = {x+y:0 for x in 'cd' for y in 'ab'}
>>> j
{'cb': 0, 'ca': 0, 'db': 0, 'da': 0}