+ 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!
2 RĂ©ponses
+ 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)]
+ 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) )