具体答复
使用列表理解:
In [2]: list1 = [1,2,3,4,5,6]
In [3]: [x+170 for x in list1]
Out[3]: [171, 172, 173, 174, 175, 176]
With map
:
In [5]: map(lambda x: x+170, list1)
Out[5]: [171, 172, 173, 174, 175, 176]
结果列表理解速度提高了一倍:
$ python -m timeit 'list1=[1,2,3,4,5,6]' '[x+170 for x in list1]'
1000000 loops, best of 3: 0.793 usec per loop
$ python -m timeit 'list1=[1,2,3,4,5,6]' 'map(lambda x: x+170, list1)'
1000000 loops, best of 3: 1.74 usec per loop
一些基准测试
在 @mgilson 发表关于 numpy 的评论后,我想知道它是如何叠加的。我发现对于少于 50 个左右元素的列表,列表理解速度更快,但 numpy 的速度更快。