简体   繁体   中英

How to sum the values from one list to a specific section of another list in python?

I need to sum the values from a list to a specific section of a another list.

For example:

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, ...]

I need a fast method because it will be repeated several times in a row and it shouldn't iterate through the whole list cause it is quite long (ca. 1000 elements). The indexes where the summation should be, are known.

Thx for any kind of help!

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]

You could try something like this:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM