Home > Software engineering >  How do I sort nested list of tuples with letter and number combinations
How do I sort nested list of tuples with letter and number combinations

Time:05-11

I need to sort my nested list of tuples first on the integer (second element) then on the string/number combination (first element). I am trying to get the first element to be in ascending order after the second element is sorted. A good example is the tuples with 2nd element of 10. d522 should be the first tuple in the group of tens.

Expected output example

#[[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11), ('d114', 11), ('d522', 10),('d717', 10),('d792', 10)]
tupple=[[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11), ('d114', 11), ('d792', 10), ('d717', 10),('d522', 10)],
        [('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11)]]

for item in tupple:
    sorted(item, key=lambda element: (element[1], (int("".join([i for i in element[0] if i.isdigit()])))),reverse=True)
# new = [[item[0] for item in inner] for inner in tupple]
tupple

###output  [[('d51', 23),  ('d874', 20),  ('d486', 15),  ('d329', 12),  ('d1328', 11), ('d1268', 11),  ('d114', 11),  ('d792', 10),  ('d717', 10),  ('d522', 10)], [('d51', 23),  ('d874', 20),  ('d486', 15),  ('d329', 12),  ('d1328', 11),  ('d1268', 11)]]

CodePudding user response:

You can force the second part of the key to be the other way around. In this case, that is fairly easy: just put a minus sign in front of the created number, and the (secondary) comparison is inverted.

(You also forgot to assign the result of sorted() back to tupple[i], since sorted() returns a copy; it doesn't alter item in place, in contrast to item.sort(). But I find tupple[i] = sorted(...) clearer here.

tupple=[[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11), ('d114', 11), ('d792', 10), ('d717', 10),('d522', 10)],
        [('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11)]]

for i, item in enumerate(tupple):
    tupple[i] = sorted(item, key=lambda element: (element[1], -int("".join(i for i in element[0] if i.isdigit()))), reverse=True)
    # Or alternatively
    # item.sort(key=lambda element: (element[1], -int("".join(i for i in element[0] if i.isdigit()))), reverse=True)
tupple

which results in

[[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d114', 11), 
('d1268', 11), ('d1328', 11), ('d522', 10), ('d717', 10), ('d792', 10)], 
[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1268', 11), ('d1328', 11)]]
  • Related