[英]Keep arrays at same size if array 0 changes
So I have an array which looks like this: A = [[],[0]]
所以我有一个看起来像这样的数组:
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
. 我想要的是每次数组
A[0]
的大小更改时, A[1]
大小也应更改,但每个条目均为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: OUTPUT:
[[], [0]]
[[1, 2, 3, 4], [0, 0, 0, 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.