Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange tuple of tuples in Python

I have a tuple of tuples:

t = ((1, 'one'), (2, 'two'))

I need it in the following format:

((1, 2), ('one', 'two'))

How can I convert it? I can do something like:

digits     =  tuple ( digit for digit, word in t )
words      =  tuple ( word for digit, word in t )
rearranged =  tuple ( digits, words )

But that seems not elegant, I suppose there's a more straightforward solution.

like image 551
lizarisk Avatar asked Apr 16 '13 14:04

lizarisk


People also ask

How do you sort tuples of tuples?

In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().

Does sort () work on tuples?

Sort elements in a tupleTo sort elements of a tuple, we can use the sorted function, providing the tuple as the first argument. This function returns a sorted list from the given iterable, and we can easily convert this list into a tuple using the built-in function tuple.

Can I sort a list of tuples Python?

If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.

Can you change the order of a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.


1 Answers

Use the following:

tuple(zip(*t))
like image 72
Elmar Peise Avatar answered Sep 18 '22 10:09

Elmar Peise