简体   繁体   English

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

[英]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.

相关问题 在numpy数组列中插入一个值,并保持相同的大小/行值 - Insert a value in a numpy array column and keep the same size / row values 强制n维数组内的数组具有相同的大小 - force the arrays inside n dimensional array to have the same size 沿 z 轴的中位数堆叠两个 3D numpy 数组并保持较小数组的大小 - Stacking two 3D numpy arrays along the median of the z-axis and keep the size of the smaller array numpy:二维数组,删除奇数索引并保持相同的数组格式 - Numpy: two dimensional arrays, delete the odd indexes and keep the same array format 通过分组使两个数组具有相同的大小 - Making two arrays the same size by grouping 2个相同大小的数组中的for循环给出ValueError - For loop in 2 arrays of same size gives ValueError python-在具有相同“外部”大小的数组之间广播 - python - broadcasting between arrays with the same 'outer' size 将 dataframe 中的 arrays 拉伸为相同大小 - Stretch arrays in dataframe to all be the same size 如何在Python中制作相同大小的数组 - How to make arrays of same size in Python cv.bitwise_and,错误:(-209:大小不匹配)操作既不是“数组操作数组”(其中 arrays 具有相同的大小和类型) - cv.bitwise_and, error: (-209:Sizes do not match) The operation is neither 'array op array' (where arrays have the same size and type)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM