welp,从示例中可以看出,进入目标列表的项目不会与源列表中的索引重叠 - 如果可以保证您可以执行以下操作:
list_of_lists = [ # broken list 1
[[0, 0, 0, 0, 0, 3, 3, 3],
[0, 0, 0, 0, 2, 0, 0, 0, 2],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, -2],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3, -3, -3]],
[# broken list 1
[0, 0, 0, 0, 0, 3, 3, 3],
[0, 0, 0, 0, 2, 0, 0, 0, 2],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, -2],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3, -3, -3]],
]
def combine_broken_list(lists):
max_size = max(map(len, lists)) # get target list size
result = [0] * max_size # initialize target list to zeros - if nothing target is zero, then this will stay that way
for sublist in lists:
found_ix = 0 # when we find a nonzero, we know we do not need to look before it again, since we start at 0.
for i, x in enumerate(sublist[found_ix:]):
if x != 0: # iterate and find non zeros
found_ix = i
result[i] = sublist[i] # set target value to source value
return result
# run on several broken lists
result = list(map(combine_broken_list, list_of_lists))
print(result) # show result
# test result 1
tgt = [0, 0, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -2, -1, 0, 0, 0 ]
print(result[0] == tgt)
# >True
如果该保证不存在,那么优先规则是什么?
numpy 可能有一个更有效的解决方案,但这应该可行。