[英]Add 2 list of lists with different lengths
我有2個清單。 列表1(比如X)是=
[ 0 , 0 , 0 , 0 ]
列表2是列表的列表(Say Y),其總是具有4的倍數的行大小但是行大小可能不相同。
例如 -
[[1,2,3,4,5,6,7,8] , [1,2,3,4]]
我想找到4個組中的逐列元素
因此,對於這個例子,總和將是[2,4,6,8] [5,6,7,8]
目前,我正在使用X = [sum(e) for e in zip(X , Y[j][count:count+4])]
其中count是固定的,用於一次完整的遍歷遍歷。 所以說Y中的列數是200.因此,對於4個數組的每個遍歷,count將保持相同(用於切割矩陣)
但是,只要最后4個元素的行長度發生變化,X就會變空。 一旦Y完全遍歷列,計數就會增加。
請詢問任何進一步的細節。 如果需要,我還可以提供一個包含矩陣和我當前使用的代碼的文本文件形式的最小可重現示例。
不完全確定問題中的所有內容是如何組合在一起的,但對於“具有不同長度的壓縮列表”問題,可以使用fillvalue=0
itertools.zip_longest
。 然后,您可以在第二步中將得到的和列表細分為塊。
>>> lsts = [[1,2,3,4,5,6,7,8] , [1,2,3,4]]
>>> from itertools import zip_longest
>>> sums = [sum(x) for x in zip_longest(*lsts, fillvalue=0)]
>>> [sums[i:i+4] for i in range(0, len(sums), 4)]
[[2, 4, 6, 8], [5, 6, 7, 8]]
使用grouper
是另一種方法:
from itertools import zip_longest
y = [[1,2,3,4,5,6,7,8] , [1,2,3,4]]
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
[[sum(t) for t in l] for l in grouper(zip_longest(*y, fillvalue=0), 4)]
輸出:
[[2, 4, 6, 8], [5, 6, 7, 8]]
不太優化的解決方案:
y = [
[1,2,3,4,5,6,7,8],
[1,2,3,4],
[1,2,3,4,5,6,7,8,10,11,12,13]
]
# Statge-1 get the max column length
max_cols = len(max(*y))
# Stage-2 if any of them is having the cols less than max_cols,
# then fill with 0
word_list1 = [i if len(i) == max_cols else i+[0]*(max_cols-len(i)) for i in y]
# Stage-3 sum the elements of corresponding columns
sum_the_list = [sum(x) for x in zip(*word_list1)]
# or list(numpy.sum(word_list1, 0))
# Stage-4 if required create the sub-lists
sum_the_list1 = [sum_the_list[l:l+4] for l in range(0, max_cols, 4)]
#### Output ####
Stage1
[
[1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0],
[1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13]
]
Stage2
[3, 6, 9, 12, 10, 12, 14, 16, 10, 11, 12, 13]
Stage3
[
[3, 6, 9, 12],
[10, 12, 14, 16],
[10, 11, 12, 13]
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.