如果数组0更改,则保持数组大小相同

问题描述 投票:1回答:2

所以我有一个看起来像这样的数组:A = [[],[0]] 通过我的脚本,第一个数组将改变大小,所以它看起来像这样:

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

我想要的是每次数组A[0]的大小变化,A[1]也应该改变大小,但每个条目都是0。 所以最后我希望它看起来像这样:

A = [[1,2,3,4],[0,0,0,0]]
python arrays
2个回答
2
投票

您无法“自动”执行此操作 - 您需要定义逻辑以在更新一个子列表时更新其他子列表。例如,您可以使用自定义函数附加到子列表并展开其他子列表:

A = [[], [0]]

def append_and_expand(data, idx, val):
    data[idx].append(val)
    n = len(data[idx])
    for lst in data:
        lst.extend([0]*(n-len(lst)))
    return data

res = append_and_expand(A, 0, 3)  # [[3], [0]]
res = append_and_expand(A, 0, 4)  # [[3, 4], [0, 0]]

1
投票
A = [[],[0]]

print(A)
if not A[0]:    # To check if the first list is empty
    A[1] = []   # Set the second one to null
    for i in range(1, 5):     # Some iteration/method of yours already working here
        A[0] = A[0] + [i]     # Some iteration/method of yours already working here
        A[1] = A[1] + [0]     # Adding the `0` each time inside that iteration

print(A)

OUTPUT:

[[], [0]]

[[1, 2, 3, 4], [0, 0, 0, 0]]
© www.soinside.com 2019 - 2024. All rights reserved.