[英]How to sum the values from one list to a specific section of another list in python?
我需要將列表中的值與另一個列表的特定部分相加。
例如:
a = [... , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...]
b = [3, 3, 3]
...
ab = [..., 1, 1, 1, 1, 1, 4, 4, 4, 1, 1, 1, 1, ...]
我需要一個快速的方法,因為它會連續重復多次,並且它不應該遍歷整個列表,因為它很長(大約 1000 個元素)。 求和應該在的索引是已知的。
感謝您提供任何幫助!
a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = [3, 3, 3]
start_index = 5
for ind, _ in enumerate(b):
a[start_index + ind] += b[ind]
print(a)
[1, 1, 1, 1, 1, 4, 4, 4, 1, 1, 1, 1]
你可以嘗試這樣的事情:
a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = [3, 3, 3]
def add_at_index(list1, list2, index_start):
for idx, v in enumerate(b):
a[idx + index_start] += b[idx]
return a
print(add_at_index(a, b, 4))
def merge_list(list1, list2, index):
if index + len(list2) > len(list1):
print("Invalid Index")
return None
for i in range(0, len(list2)):
list1[index + i] += list2[i]
return list1
# Main
a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = [3, 3, 3]
# Choose an index in the third argument of the function
print(merge_list(a, b, 5))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.