How can I sort a "zip-list" after integer and not string? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I sort a "zip-list" after integer and not string?

Hi! I used the zip function to merge three lists. One list consist of integers and the other two consist of strings. If I use sort now my "zip-list" is sorted alphabetical but I want it to be sorted after the integer in the list. Example: zip-list.sort() My output: [(a, e, 4), (b, f, 1), (c, g, 3), (d, h, 2)] But I want it to be: [(b, f, 1), (d, h, 2), (c, g, 3), (a, e, 4)] I hope someone can help me. Thank you!

11th May 2020, 8:33 AM
🌱Zuhal🐛🌿
🌱Zuhal🐛🌿 - avatar
2 Answers
+ 4
This can be done with a lambda and a custom key: ( sorting is done by index 2 = third element in tuple) lst = [('a','f',3), ('k','c',1), ('l','f',0)] res = sorted(lst,key=lambda x : x[2]) print(res) # output = [('l', 'f', 0), ('k', 'c', 1), ('a', 'f', 3)]
11th May 2020, 8:45 AM
Lothar
Lothar - avatar
+ 1
must the list look exactly like the output you wanted? one way i can think if is put the int first of the 3 elements (1, b, f)- then zip-list.sort(). Then use for loop to rearrange the seqence of the tuple in the list again. ie. new_list= [] for a, b, c in zip_list: new_list.append( (b, c, a) )
11th May 2020, 8:45 AM
Aurore, Ya Ting Tan
Aurore, Ya Ting Tan - avatar