python - 添加到整数列表的列表

标签 python list function add

我有一个列表 x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]。 我想将 y = 400 添加到列表中的每个元素。 输出应为 z = [3273, 5721, 5821], 3188, 5571, 5671], [3188, 5571, 5671]]

我试过用

def add(x,y): 
addlists=[(x[i] + y) for i in range(len(x))]    
return addlists
z = add(x,y) 

但这没有用。

我也试过

def add(x,y):
addlists = [(x[i] + [y]) for i in range(len(x))]
    return addlists
z = add(x,y) 

但是返回 z = [[2873, 5321, 5421] + 400, [2788, 5171, 5271] + 400, [2788, 5171, 5271]+ 400]

最佳答案

作为另一种方法,如果您想使用 numpy您可以使用以下内容。

根据数据集的大小,这种方法可能会比使用嵌套循环提供一些效率提升,因为 numpy 使用一种称为 'broadcasting' 的方法将给定操作应用于数组中的每个值,而不是“传统的循环”。

此外,这种方法可以很好地扩展,因为它可以灵活地适应列表的形状。

例如:

import numpy as np

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]
a = np.array(x)

a + 400

输出:

array([[3273, 5721, 5821],
       [3188, 5571, 5671],
       [3188, 5571, 5671]])

更新:

此更新解决了以下评论问题:

... is it possible to add to only the 2 last elements in each of the list in the array ...

是的,绝对 - 使用切片。这是一个链接 simple slicing tutorial .

例如:

a[:,-2:] += 400

输出:

array([[2873, 5721, 5821],
       [2788, 5571, 5671],
       [2788, 5571, 5671]])

解释:

a[:,-2:] += 400
^ ^  ^    ^
| |  |    |
| |  |    \ Apply the addition in place.
| |  |
| |  \ Apply the addition to only the last 2 elements.
| |
| \ Apply the addition to all arrays.
|
\ Array to be sliced

关于python - 添加到整数列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74393232/

相关文章:

python - python 获取函数的返回值并将其更改为 int

function - 为什么 Scala 类方法不是一等公民?

python - dyld : Library not loaded:/usr/local/libodep/lib/libintl. 8.dylib

r - R中的向量列表-提取向量的一个元素

c++ - 使用列表对象内部对象的派生函数

c# - List<T>.Enumerator IEnumerator.Reset()方法实现

postgresql - SQL 状态 : 42883, 没有函数匹配给定的名称和参数类型。但是这个功能确实存在

python - 了解 Selenium Web 元素列表

python - 如何在Bubble_sort程序中获得最小遍历次数(Python编程)

python - 运行 python 脚本时出错