Sum of elements stored inside a tuple

Sum of elements stored inside a tuple,第1张

Sum of elements stored inside a tuple

You can use

map
and
sum
function like
this

>>> li = [(1, 2), (1, 3), (2, 3)]>>> map(sum, li)[3, 4, 5]

Alternatively you can use list
comprehension, like this

>>> [sum(tup) for tup in li][3, 4, 5]

Note: I personally prefer the list comprehension version, because

map
function in
Python 3.x will return an iterable
map
object, which needs to be explicitly
converted to a list, like this
list(map(sum, li))
.

>>> li = [(1, 2), (1, 3), (2, 3)]>>> map(sum, li)<map object at 0x7f3dc25bb0f0>>>> type(map(sum, li))<class 'map'>>>> list(map(sum, li))[3, 4, 5]

But list comprehension will give a list in both Python 2.x and Python 3.x.



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5648599.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存