对数组执行操作并将结果存储在列表列表中

2024-04-25 21:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想对一个列表执行多次操作,这样我的输出就是一个包含可能的输出组合的列表列表。在这种情况下,我想从列表中减去一个值一次,但对每个元素重复它。所以在这个例子中,我想从列表中的一个元素中减去一个,存储它,然后对下一个元素重复:

input1 = [1, 2, 3, 0, 4]
output1 = [[0, 2, 3, 0, 4], [1, 1, 3, 0, 4], [1, 2, 2, 0, 4], [1, 2, 3, 0, 3]]

这些值总是整数,如果值小于1,则函数不会从中减去。你知道吗

现在我有一个while循环,每当input1中的值大于等于1时,就用list input1填充一个列表。我做了第二个while循环来尝试完成减法,但它只是从任何一个数>;=1中减去1。你知道吗

i = 0
input1 = [1, 2, 3, 0, 4]
output1 = []
while i < int(len(input1)):
    if input1[i] >= 1:
        print('i: ' + str(i))
        print(input1[i])
        output1.append(input1)
    i += 1
print(output1)
j = 0
k = 0
while j < int(len(output1)) or k < int(len(input1)):
    print('j: ' + str(j) + ', k: ' + str(k))
    if output1[j][k] < 1:
        print(output1[j][k])
        k += 1
    elif output1[j][k] >= 1:
        output1[j][k] = output1[j][k] - 1
        print(output1[j][k])
        k += 1
        j += 1
print(output1)

使用此代码,在最后一行output1打印:

[[0, 1, 2, 0, 3], [0, 1, 2, 0, 3], [0, 1, 2, 0, 3], [0, 1, 2, 0, 3]]

这里出了什么问题?有没有更有效的方法来做到这一点,也许是使用itertools?你知道吗


Tags: 函数元素列表lenif情况整数list
3条回答

下面是一些使用enumerate生成器生成的代码,这些代码比其他代码更具python风格。enumerate返回一对数字:第一个是列表中项目的索引,第二个是项目本身。你知道吗

input1 = [1, 2, 3, 0, 4]
output1 = []
for ndx, item in enumerate(input1):
    if item >= 1:
        tempoutput = input1[:]  # a copy of the list
        tempoutput[ndx] -= 1
        output1.append(tempoutput)

变量output1现在具有所需的值

[[0, 2, 3, 0, 4], [1, 1, 3, 0, 4], [1, 2, 2, 0, 4], [1, 2, 3, 0, 3]]

您的原始代码不起作用,因为您犯了一个常见的错误。你在你的第一个部分建立了output1

output1.append(input1)

但这只是将另一个引用添加到output1的输入列表中,而不是添加一个副本。当您更改output1的任何一个子列表时,它们都会同时被修改,因为它们实际上都是同一个列表。您应该添加一个带有

output1.append(input1[:])

(请注意,我在代码中使用相同的技巧来获取列表的副本。)当对代码进行更改时,它会给出正确的答案。你知道吗

下面是一个基本版本,它实现了您所描述的功能,改进后的版本将作为一个练习留给读者:

input = [1, 2, 3, 0, 4]
output = []

for i, item in enumerate(input):
    current = input[:]
    current[i] = item - 1 if item > 0 else item
    output.append(current)

编辑:如果当前元素小于1(如注释所示),则应跳过整个操作,则解决方案为:

input = [1, 2, 3, 0, 4]
output = []

for i, item in enumerate(input):
    if item > 0:
        current = input[:]
        current[i] -= 1
        output.append(current) 

如果您愿意使用第三方库,numpy很方便:

import numpy as np

input1 = np.array([1, 2, 3, 0, 4])

n = len(input1)
arr = np.tile(input1, (n, 1))
res = (arr - np.eye(n))[np.where(input1 >= 1)]

结果

array([[ 0.,  2.,  3.,  0.,  4.],
       [ 1.,  1.,  3.,  0.,  4.],
       [ 1.,  2.,  2.,  0.,  4.],
       [ 1.,  2.,  3.,  0.,  3.]])

解释

  • 使用numpy.tile创建形状(n, n)的数组。你知道吗
  • 减去恒等式numpy.eye,从对角线中减去1。你知道吗
  • 使用numpy.where过滤正输入。你知道吗

为什么要用numpy?

  • 性能:Python循环比向量化的numpy计算慢。你知道吗
  • 内存:numpy比Python列表更有效地保存数字数据。你知道吗
  • 语法:关注数字逻辑而不是多个for&;if语句。你知道吗

相关问题 更多 >