python dict理解有两个范围

时间:2013-09-13 14:50:10

标签: python dictionary list-comprehension

我正在尝试生成一些代码,例如:

{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}

我该如何解决?

感谢

4 个答案:

答案 0 :(得分:6)

使用zip

>>> dict(zip(range(1,5), range(7,11)))
{1: 7, 2: 8, 3: 9, 4: 10}

使用dict comprehension

>>> {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}