[英]How to form a new tuple with the first value of each tuple of a tuple of tuples?
I want to form a tuple with the first elements of each tuple. 我想用每个元组的第一个元素组成一个元组。 Im a beginner in python, maybe this is an easy one but i cant find a way to do it plz help. 我是python的初学者,也许这很简单,但是我找不到找到它的方法。
ex: 例如:
input 输入
x = (('A','B','C'),('D','E','F'),('G','H','I'))
output: 输出:
y= ('A', 'D', 'G')
x = (('A','B','C'),('D','E','F'),('G','H','I'))
for each in zip(*x):
print(each)
prints: 印刷品:
('A', 'D', 'G')
('B', 'E', 'H')
('C', 'F', 'I')
Use the zip()
function. 使用zip()
函数。 Read more here. 在这里阅读更多。
Edited: 编辑:
like CAB says if you just want the first one you can do: 就像CAB所说的,如果您只想要第一个,则可以执行以下操作:
y = zip(*x)[0]
Use comprehension and convert to a tuple; 使用理解并转换为元组;
>>> x = (('A','B','C'),('D','E','F'),('G','H','I'))
>>> y = tuple([l[0] for l in x])
>>> y
('A', 'D', 'G')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.