Python字典理解示例 [英] Python dictionary comprehension example
本文介绍了Python字典理解示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试学习Python字典理解,我认为有可能在一行中做以下功能。我不能像第一个那样使 n + 1
,或者避免使用 range()
I am trying to learn Python dictionary comprehension, and I think it is possible to do in one line what the following functions do. I wasn't able to make the n+1
as in the first or avoid using range()
as in the second.
是否可以使用在理解期间自动递增的计数器,如 test1()
?
Is it possible to use a counter that automatically increments during the comprehension, as in 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
推荐答案
使用 枚举
功能:
>>> L = ['a', 'b', 'c', 'd']
>>> {letter: i for i,letter in enumerate(L, start=1)}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
请注意,如果您想要反向映射,即映射 1
to a
, 2
to b
etc,you可以简单地做:
Note that, if you wanted the inverse mapping, i.e. mapping 1
to a
, 2
to b
etc, you could simply do:
>>> dict(enumerate(L, start=1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
这篇关于Python字典理解示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文