简体   繁体   中英

Summing lists elements using zip

I am trying to sum up lists vertically but facing below issues. Example 1 below shows the sample how I need the output as. Example 2 below shows the problem I am facing.

Example 1:

list1 = [111]
list2 = [222]
sum_list = []

for (item1, item2) in zip(list1, list2):
    sum_list.append(item1+item2)

print(sum_list)    # [333]

Example 2:

inp = "1111 2222"
list1 = inp.split()
#print(list1)
list2 = [int(i) for i in list1]
print(list2)   # [1111, 2222]
out = [sum(item) for item in zip(list2)]

print(out)   # [1111, 2222]

I need the out as [3333] (as mentioned like Example 1 above) but it is printing as [1111, 2222].

You should just sum list2 and put it inside an array.

inp = "1111 2222"
list1 = inp.split()
list2 = [int(i) for i in list1]
print(list2) # [1111, 2222]
out = [sum(list2)]

print(out)   # [333]

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