簡體   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