How to perform an operation on this tuple and convert to another tuple in Python?
我有一个像这个
怎么能做到?
我使用的是python 2.7。谢谢您。
当你需要一个"transpose"的战略,或者之类的东西,想
1 2 | a = ( ('Col1', 1, 11), ('Col2', 2, 22), ('Col3', 3, 33) ) print zip(*a)[0] |
输出:
1 | ('Col1', 'Col2', 'Col3') |
编辑部一位有趣的细节:
1 | zip(('Col1', 1, 11), ('Col2', 2, 22), ('Col3', 3, 33)) |
这结果在
1 | [('Col1', 'Col2', 'Col3'), (1, 2, 3), (11, 22, 33)] |
这看起来像一个transpose元组的原创,如果你把它作为一个矩阵。grabbing第一单元的输出通过zipped
试试下面的:
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) |