如何在这个元组上执行操作并转换为Python中的另一个元组?

How to perform an operation on this tuple and convert to another tuple in Python?

我有一个像这个( (Col1, x, x), (Col2, x, x), (Col3, x, x) )的元组我想把它转换成另一个tuple,看起来像这个(Col1, Col2, Col3)

怎么能做到?

我使用的是python 2.7。谢谢您。


当你需要一个"transpose"的战略,或者之类的东西,想zip。试试这个:

1
2
a = ( ('Col1', 1, 11), ('Col2', 2, 22), ('Col3', 3, 33) )
print zip(*a)[0]

输出:

1
('Col1', 'Col2', 'Col3')

编辑部一位有趣的细节:

*放映《冰unpack用于Python的两个参数的列表。在其他的话,我translates两个以上zip(*a)

1
zip(('Col1', 1, 11), ('Col2', 2, 22), ('Col3', 3, 33))

这结果在

1
[('Col1', 'Col2', 'Col3'), (1, 2, 3), (11, 22, 33)]

这看起来像一个transpose元组的原创,如果你把它作为一个矩阵。grabbing第一单元的输出通过zipped [0]desired提供这样的输出。


试试下面的:

1
tuple(x[0] for x in big_tuple)

实例:

1
2
3
4
>>> big_tuple = ((0,1,1), (1,0,0), (2,3,3))
>>> tuple(x[0] for x in big_tuple)
(0, 1, 2)
>>>


1
2
3
tup_tuples = (("Col1","x","x"), ("Col2","x","x"), ("Col3","x","x") )
print tuple(first for first, _, _ in tup_tuples)
# ('Col1', 'Col2', 'Col3')


试试这个:

1
2
tuples = ( (Col1, x, x), (Col2, x, x), (Col3, x, x) )
filtered = tuple(t[0] for t in tuples)