简体   繁体   中英

list elements sum of one list first element to last element of second list

How to sum first element of one list to last element of second list if both list contains same amount of elements in python.

Source code (should be kind of like this):

def update(l1,l2,l3):
    for i in range(len(l1)):
        l3.append(l1[i] + l2[-i]) #i know -i is not correct way to start indexing in reverse

l1=[1,2,3,4,5]
l2=[6,7,8,9,10]
l3=[]
update(l1,l2,l3)
print(l1)
print(l2)
print(l3)

It would mean a lot if someone could help me with this problem.

If you subtract the index from the length of the list, you add the first item and the last item consecutively.

# The expression l2[len(l2)-i-1] iterates from  the last element to the first element.
def update(l1,l2,l3):
    for i in range(len(l1)):
        l3.append(l1[i] + l2[len(l2) - i - 1])

l1=[1,2,3,4,5]
l2=[6,7,8,9,10]
l3=[]
update(l1,l2,l3)
print(l1, l2, l3)

Output:

[1, 2, 3, 4, 5] [6, 7, 8, 9, 10] [11, 11, 11, 11, 11]

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