繁体   English   中英

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

[英]Keep arrays at same size if array 0 changes

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

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

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

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

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

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]]
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]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM