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.
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 ().
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.
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.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
Use the following:
tuple(zip(*t))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With