Python 按增量增加所有列表值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17005536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increase all of a lists values by an increment
提问by i love crysis
I think I'm having a idiot moment,
我想我有一个白痴的时刻,
I have a list and I need to add 170 to each number
我有一个列表,我需要为每个数字添加 170
list1[1,2,3,4,5,6,7,8......]
list2[171,172,173......]
采纳答案by Matthew Adams
Specific answer
具体答案
With list comprehensions:
使用列表理解:
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:
与map:
In [5]: map(lambda x: x+170, list1)
Out[5]: [171, 172, 173, 174, 175, 176]
Turns out that the list comprehension is twice as fast:
事实证明,列表理解的速度是原来的两倍:
$ 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
Some bench-marking
一些基准测试
After @mgilson posted the comment about numpy, I wondered how it stacked up. I found that for lists shorter than 50 or so elements, list comprehensions are faster, but numpy is faster beyond that.
在@mgilson 发表了关于 numpy 的评论后,我想知道它是如何堆积起来的。我发现对于少于 50 个左右元素的列表,列表理解更快,但 numpy 更快。


回答by Amber
incremented_list = [x+170 for x in original_list]

