如果数组0发生变化,则保持数组大小相同

时间:2019-01-29 12:16:05

标签: python arrays

所以我有一个看起来像这样的数组:A = [[],[0]]
通过我的脚本,第一个数组的大小将发生变化,因此它将如下所示:

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

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

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

2 个答案:

答案 0 :(得分: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 :(得分: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)

输出:

[[], [0]]

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