我有一个列表 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/