Python字典理解示例

ste*_*nci 5 python dictionary dictionary-comprehension

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

是否可以使用在理解过程中自动递增的计数器,如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
Run Code Online (Sandbox Code Playgroud)

Bak*_*riu 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}
Run Code Online (Sandbox Code Playgroud)

需要注意的是,如果你想逆映射,即映射1a,2b等,你可以简单地做:

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