Python字典理解示例

时间:2013-07-07 16:19:58

标签: python dictionary dictionary-comprehension

我正在尝试学习Python字典理解,我认为可以在一行中完成以下函数的功能。我无法像第一个那样制作n+1,或者避免在第二个中使用range()

是否可以使用在理解过程中自动递增的计数器,如test1()

def test1():
    l = ['a', 'b', 'c', 'd']
    d = {}
    n = 1
    for i in l:
        d[i] = n
        n = n + 1
    return d

def test2():
    l = ['a', 'b', 'c', 'd']
    d = {}
    for n in range(len(l)):
        d[l[n]] = n + 1
    return d

2 个答案:

答案 0 :(得分:10)

使用enumerate函数非常简单:

>>> L = ['a', 'b', 'c', 'd']
>>> {letter: i for i,letter in enumerate(L, start=1)}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

请注意,如果您想要逆映射,即将1映射到a2b等,您只需执行以下操作:

>>> dict(enumerate(L, start=1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

答案 1 :(得分:1)

这有效

>>> l = ['a', 'b', 'c', 'd']
>>> { x:(y+1) for (x,y) in zip(l, range(len(l))) }
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
相关问题