简体   繁体   中英

how to sort list of tuples in python with different size and element size

Can someone help me in sorting below tuple in Python?

({'b', 'c', 'a'}, {('b', 'c'), ('a', 'b')})

Expected output:

({'a', 'b', 'c'}, {('a', 'b'), ('b', 'c')})

I'm assuming you're talking about a list of lists and that you want to first sort each list and then the whole list of lists.

You can do it as follows:

arr = [['b','c','a'],['b','c'],['a','b']]

for i in arr:
    i.sort()

arr.sort(key=lambda x:x[0])

print(arr) 

[['a', 'b', 'c'], ['a', 'b'], ['b', 'c']]

Remember the solution will be totally different if you have a tuple of sets or vice versa.

Your title and example are conflicting. You should consult the python documentation on set , tuple , and list

Some Examples:

a_list = ['b', 'c', 'a']
a_tuple = ('b', 'c', 'a')
a_set = {'b', 'c', 'a'}
a_list_of_tuples = [('b', 'c', 'a'), ('b', 'c'), ('a', 'b')]
a_list_of_tuples_and_lists = [('b', 'c', 'a'), [('b', 'c'), ('a', 'b')]]

This example works for both a list of lists/tuples and a tuple of sets/tuples, however it returns an actual list of tuples not a tuple of sets as provided in your expected output example.

my_list = [('b', 'c', 'a'), [('b', 'c'), ('a', 'b')]]
print(tuple((sorted(item) for item in my_list)))
-> (['a', 'b', 'c'], [('a', 'b'), ('b', 'c')])

my_tuple = ({'b', 'c', 'a'}, {('b', 'c'), ('a', 'b')})
print(tuple((sorted(item) for item in my_tuple)))
-> (['a', 'b', 'c'], [('a', 'b'), ('b', 'c')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM