Python:如何根据字典转换列表的每个元素?

时间:2015-12-24 10:30:36

标签: python

如何根据字典转换列表的每个元素? 例如: 我有清单:

l = [0,1,2,3,2,3,1,2,0]

我有一本字典:

m = {0:10, 1:11, 2:12, 3:13}

我需要获得列表:

[10, 11, 12, 13, 12, 13, 11, 12, 10]

1 个答案:

答案 0 :(得分:-1)

有几种方法可以做到这一点:

In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

所以列表理解是最快的方法。