Home > Mobile >  Sort tuple containing various data types in Python
Sort tuple containing various data types in Python

Time:10-26

I'm faced with the following tuple containing several various datatypes:

my_test_tuple = ( ["David", 3.14], [34, "Zak"], ["Colin", 54], [34, "Xerxes", True], ["Fred"] )

I need to sort it by the names alphabetically in descending order.

The output should look the following:

print(sort_tuple (my_test_tuple))
(['Colin', 54], ['David', 3.14], ['Fred'], [34, 'Xerxes', True], [34, 'Zak'])

There are numerous resources on how to sort a tuple by the first position in the tuple, problem here is that not all the names are in the first position.

Any help on how to proceed would be appreciated!

Tried using lambda but it was only useful for when data types are stored in a specific position.

CodePudding user response:

You can extract the names with list comprehension and then sort the original tuple/list based on the order of the new list you created:

names_tuple = [item[sub_item] for item in my_test_tuple for sub_item in item if type(sub_item) == str]
sorted_list = tuple([x for _,x in sorted(zip(names_tuple, my_test_tuple))])

CodePudding user response:

you cant sort tuples
they are an immutable data structure

if you want to sort the values of the tuple
sort the values before creating the tuple
or do the answer above.

  • Related