简体   繁体   English

如何用元组中每个元组的第一个值构成一个新元组?

[英]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.

相关问题 根据每个元组的第一个值比较两个元组列表(但返回所有元组值) - Comparing Two Lists of Tuples Based On Each Tuple's First Value (But Returning ALL Tuple Values) 将新元组加入Python中的第一个元组列表 - join new tuple to first list of tuples in Python 为每个元组添加第一个值 - Add first value for each tuple 如何在 Python 中的元组列表中对每个元组中的第一个值求和? - How do I sum the first value in each tuple in a list of tuples in Python? 如何根据每个元组中第一个数字的值从元组列表中弹出项目? - How do I pop item off a list of tuples, based on the value of the first number in each tuple? 如何使用每个元组的第一个值作为键将六个元组列表连接到 Pandas 数据框中? - How do I join six list of tuples into a pandas dataframe using the first value of each tuple as the key? 如何将元组列表转换为 Pandas 数据框,以便每个元组的第一个值代表一列? - How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column? 如何基于第一个值Python替换元组排序列表中的元组 - How to replace a tuple in sorted list of tuples basing on first value Python 如何将元组元组中的变量更改为具有所需值的元组 - How to change a variable in a tuple of tuples to a tuple with wanted value 将元组添加到元组的元组 - Adding a tuple to a tuple of tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM