对Python中的列表(或数组)中的每个元素求和一个数字 [英] Sum one number to every element in a list (or array) in Python
本文介绍了对Python中的列表(或数组)中的每个元素求和一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这里,我再次提出基本问题,但请忍受.
Here I go with my basic questions again, but please bear with me.
在Matlab中,将数字添加到列表中的元素非常简单:
In Matlab, is fairly simple to add a number to elements in a list:
a = [1,1,1,1,1]
b = a + 1
b
然后是[2,2,2,2,2]
在python中,这似乎不起作用,至少在列表上如此.
In python this doesn't seem to work, at least on a list.
是否有一种简单的快速方法可以将单个数字加到整个列表中.
Is there a simple fast way to add up a single number to the entire list.
谢谢
推荐答案
如果要处理数字列表,最好使用NumPy数组:
if you want to operate with list of numbers it is better to use NumPy arrays:
import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2
给予
[3, 3, 3, 3, 3]
这篇关于对Python中的列表(或数组)中的每个元素求和一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文