使用函数在指定索引处开始Python中不同长度的列表 [英] Summing lists of different lengths in Python beginning at a specified index using a function
问题描述
如何将多个列表从列表中的指定索引开始组合起来,同时也将各个索引的值相加?
How can I combine multiple lists starting at a specified index within one of the lists, while also summing the values at the respective indexes?
如果我有3个列表:
If I had 3 lists:
a = [1, 2, 3, 4, 5, 0, 0, 0, 0]
b = [2, 3, 4, 5, 6]
c = [5, 2]
我怎么做到这一点,以便我可以在 b
和 c
列表> a ,并且各个指标会相加?
How could I make it so that I could insert lists b
and c
into any position within a
, and the respective indexes would sum?
例如,我可以从的第一个索引开始插入
b
/ code>,并从 a
的第五个索引开始插入 c
列表。这样的输出看起来像这样:
For example, I could insert list b
starting from the first index of a
, and also insert list c
starting from the fifth index of a
. The output of this would look something like:
NewList = [1, 4, 6, 8, 10, *11*, 2, 0, 0]
您可以看到,当添加列表 b
和 c
在上述 a
的索引处,第五个索引处出现重叠,我想这样做。
You can see that when adding lists b
and c
at the aforementioned indexes of a
, there was an overlap at the fifth index, which I would like to do.
我已经尝试从 itertools使用
izip_longest
code>结合切片方法:
I have tried using izip_longest
from itertools
in combination with a slicing method:
result = [sum(n) for n in izip_longest(a[2:], b, fillvalue=0)]
但是这会产生:
result = [5, 7, 9, 5, 6, 0, 0]
这会切断列表 a
中的零和一个索引,这是我不想要的。但是,我想使用 izip_longest
,因为我可以对不同长度的列表进行求和。
This cuts off the zero and one index in list a
, which I do not want. However, I want to use izip_longest
because I can sum lists with different lengths.
我想创建一个可以用任意数量的列表执行此操作的函数,因此 a
可能是一个列表中有len = 1000,我可以根据需要插入任意数量的不同长度的不同长度的列表,这些列表可以是任何我想要的 a
,并且索引值可以相加。 / b>
I would like to create a function that does this with an arbitrary amount of lists, so a
could be a list with len = 1000 and I could insert any amount of different lists with different lengths wherever I want into a
, as many times as I want and the index values would sum.
推荐答案
这是一个应该做你要求的功能:
Here is a function that should do what you're asking for:
def combine(lista, listb, index_in_list_a_to_start_insert):
# left pad list b with zeros
newb = [0]*index_in_list_a_to_start_insert + listb
# right pad shorter list
max_len = max(len(lista), len(newb))
newa = lista if len(lista) >= max_len else lista + [0]*(max_len-len(lista))
newb = newb if len(newb) >= max_len else newb + [0]*(max_len-len(newb))
# sum element-wise
return [a + b for a, b in zip(newa,newb)]
You can run your example by chaining this function as so:
a = [1, 2, 3, 4, 5, 0, 0, 0, 0]
b = [2, 3, 4, 5, 6]
c = [5, 2]
combine(combine(a, b, 1), c, 5)
输出:
Output:
[1, 4, 6, 8, 10, 11, 2, 0, 0]
您可能还想添加一些错误检查以确保指定的索引处于界限内。
You'd probably also want to add some error checking to make sure that the specified index is in-bounds.
这篇关于使用函数在指定索引处开始Python中不同长度的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!