用户登录
用户注册

分享至

将一个数字与 Python 中列表(或数组)中的每个元素相加

  • 作者: 我想取一个好长好长好长好长好长好长的
  • 来源: 51数据库
  • 2022-10-21

问题描述

在这里我再次提出我的基本问题,但请耐心等待.

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]
软件
前端设计
程序设计
Java相关