我正在尝试生成一些代码,例如:
{1:7,2:8,3:9,4:10}
和
{i:j for i in range(1,5) for j in range(7,11)}
产生
{1: 10, 2: 10, 3: 10, 4: 10}
我该如何解决?
感谢
答案 0 :(得分:6)
使用zip
:
>>> dict(zip(range(1,5), range(7,11)))
{1: 7, 2: 8, 3: 9, 4: 10}
>>> {k:v for k, v in zip(range(1,5), range(7,11))}
{1: 7, 2: 8, 3: 9, 4: 10}
>>> {x:x+6 for x in range(1,5)}
{1: 7, 2: 8, 3: 9, 4: 10}
您的代码类似于以下代码:
ret = {}
for i in range(1,5):
for j in range(7,11):
ret[i] = j
# ret[i] = 10 is executed at last for every `i`.
答案 1 :(得分:3)
{i: j for i, j in zip(range(1, 5), range(7, 11))}
答案 2 :(得分:2)
使用zip
(或itertools.izip
)和itertools.count
:
>>> from itertools import count, izip
字典-理解:
>>> {k:v for k,v in izip(xrange(1,5), count(7))}
{1: 7, 2: 8, 3: 9, 4: 10}
dict()
:
>>> dict(izip(xrange(1,5), count(7)))
{1: 7, 2: 8, 3: 9, 4: 10}
答案 3 :(得分:2)
我会使用enumerate
:
>>> dict(enumerate(range(7, 11), 1))
{1: 7, 2: 8, 3: 9, 4: 10}