简体   繁体   中英

Keep arrays at same size if array 0 changes

So I have an array which looks like this: A = [[],[0]]
Through my script the first array will change in size so it will look something like this:

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

What I want is that everytime array A[0] changes in size, A[1] should change in size too but with each entry being 0 .
So in the end I want it to look like this:

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

You can't do this "automatically" - you need to define logic to update other sublists when you update one sublist. For example, you can use a custom function to append to a sublist and expand other sublists:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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