zip 函数对元组的帮助 [英] zip function help with tuples

查看:21
本文介绍了zip 函数对元组的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能帮助我解决我遇到的问题.我有很多看起来像这样的元组(> 500):

(2,1,3,6)(1,2,5,5)(3,0,1,6)(10,1,1,4)(0,3,3,0)

我的代码片段如下:

sum1 = (A,B,C,D) # 创建 (A,B,C,D) 和的元组mysum = map(sum, zip(A, B, C, D))打印(mysum)

我意识到上面的代码不正确.我试图找到一种使用 zip 函数将所有值 A 加在一起、B 的所有值加在一起、C 的所有值加在一起以及 D 的所有值加在一起的方法.例如,我想打印如下所示的内容:

Asum = 16总和 = 7总和 = 13总和 = 21

有人可以帮忙吗?非常感谢您抽出宝贵时间.

解决方案

>>>zip((1,2,3),(10,20,30),(100,200,300))[(1, 10, 100), (2, 20, 200), (3, 30, 300)]>>>[sum(x) for x in zip((1,2,3),(10,20,30),(100,200,300))][111、222、333]

要使用任意大的元组集来做到这一点:

<预><代码>>>>myTuples = [(1,2,3), (10,20,30), (100,200,300)]>>>[sum(x) for x in zip(*myTuples)][111、222、333]

旁注:在 python3 中,请注意 zip 返回一个惰性可迭代对象,您总是可以像任何其他类型的可迭代对象一样将其显式转换为列表:list(zip(...))

(感谢 Seganku 在编辑中发现示例中的错误被其他编辑三次拒绝)

I am hoping someone can help me with a problem I'm stuck with. I have a large number of tuples (>500) that look like this:

(2,1,3,6)  
(1,2,5,5)  
(3,0,1,6)  
(10,1,1,4)  
(0,3,3,0)  

A snippet of my code reads:

sum1 = (A,B,C,D) # creates a tuple of sums of (A,B,C,D)  
mysum = map(sum, zip(A, B, C, D))
print(mysum)

I realize the above code is not correct. I am trying to find a way to add all the values A together, all the values of B together, all the values of C together, and all the values of D together using the zip function. For example, I would like to print something that looks like this:

Asum = 16  
Bsum = 7  
Csum = 13  
Dsum = 21  

Can anyone help please? Thanks very much for your time.

解决方案

>>> zip((1,2,3),(10,20,30),(100,200,300))
[(1, 10, 100), (2, 20, 200), (3, 30, 300)]

>>> [sum(x) for x in zip((1,2,3),(10,20,30),(100,200,300))]
[111, 222, 333]

To do this with an arbitrarily large set of tuples:

>>> myTuples = [(1,2,3), (10,20,30), (100,200,300)]
>>> [sum(x) for x in zip(*myTuples)]
[111, 222, 333]

sidenote: in python3, note that zip returns a lazy iterable, which you can always explicitly turn into a list like any other kind of iterable: list(zip(...))

(thanks to Seganku for catching mistake in examples in an edit which was thrice rejected by other editors)

这篇关于zip 函数对元组的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆