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