简体   繁体   中英

Add 2 list of floats together

How do i Add 2 lists that both have floats in them. Like how do I actually add the numbers?

Ive tried using sum(list1, list2) but that did not work
I've also tried list1+list2 but that didn't work either.

This sounds like a time for a list comprehension.

a = [1.0, 2.0, 3.0]
b = [1.1, 2.2, 3.3]

[x+y for x,y in zip(a,b)]

Or for functional programming.

import operator
map(operator.add, a, b)

The zip method will do. It will combine all elements of a particular index. And since all of them are floating points, just add the values

l1=[1.5,3.2,5.0,3.5]
l2=[8.5,4.7,2.5,7.6]
l3=[i+j for i,j in zip(l1,l2)]
print(l3)

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