简体   繁体   English

对Python中的列表(或数组)中的每个元素求和一个数字

[英]Sum one number to every element in a list (or array) in Python

Here I go with my basic questions again, but please bear with me. 在这里,我再次提出基本问题,但请耐心等待。

In Matlab, is fairly simple to add a number to elements in a list: 在Matlab中,将数字添加到列表中的元素非常简单:

a = [1,1,1,1,1]
b = a + 1

b then is [2,2,2,2,2] b然后是[2,2,2,2,2]

In python this doesn't seem to work, at least on a list. 在python中,这似乎不起作用,至少在列表上。

Is there a simple fast way to add up a single number to the entire list. 有没有一种简单的快速方法可以将单个数字加到整个列表中。

Thanks 谢谢

if you want to operate with list of numbers it is better to use NumPy arrays: 如果要处理数字列表,最好使用NumPy数组:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

using List Comprehension: 使用列表推导:

>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>> 

which roughly translates to using a for loop: 大致翻译为使用for循环:

>>> newL = []
>>> for x in L:
...     newL+=[x+1]
... 
>>> newL
[2, 2, 2, 2, 2]

or using map: 或使用地图:

>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>> 

You can also use map: 您还可以使用地图:

a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))

It gives: 它给:

[2, 2, 2, 2, 2]

If you don't want list comprehensions: 如果您不希望列表理解:

a = [1,1,1,1,1]
b = []
for i in a:
    b.append(i+1)

try this. 尝试这个。 (I modified the example on the purpose of making it non trivial) (我修改了这个示例,目的是使其变得不平凡)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster operator.add几乎快了两倍多

%timeit map(operator.add, a, a1)

than adding with numpy 比用numpy添加

%timeit an+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM