【问题标题】:Python dictionary comprehension examplePython 字典理解示例
【发布时间】:2013-07-05 00:47:27
【问题描述】:

我正在尝试学习 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

【问题讨论】:

  • dict理解中使用range可以吗?

标签: python dictionary dictionary-comprehension


【解决方案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}

【讨论】:

  • 谢谢,我不知道zip()。可以在理解中使用range() 吗?
  • @stenci 当然,你可以在理解中使用范围
  • 如果不想使用范围,请使用@Bakuriu 的枚举解决方案。
【解决方案2】:

使用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'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2013-07-28
    相关资源
    最近更新 更多