Python puzzler: custom list sort

#1

I’m still a python learner, so someone help me out here.

things = [
  "36767277_0_col-580_permanences"
  "36767277_10_col-580_permanences"
  "36767277_11_col-580_permanences"
  "36767277_12_col-580_permanences"
  "36767277_13_col-580_permanences"
  "36767277_1_col-580_permanences"
  "36767277_2_col-580_permanences"
  "36767277_3_col-580_permanences"
  "36767277_4_col-580_permanences"
  "36767277_5_col-580_permanences"
  "36767277_6_col-580_permanences"
  "36767277_7_col-580_permanences"
  "36767277_8_col-580_permanences"
  "36767277_9_col-580_permanences"
]

Given that the _ character is the delimiter for these strings, I want to sort this list by the 2nd column (the one with 0, 10, 11, etc.) in ascending numerical order.

What is the best way to do this in python?

0 Likes

#2
things = [t[1] for t in sorted((int(s.split("_")[1]), s) for s in things)]

To break this down:

(int(s.split("_")[1]), s) for s in things

That converts the list into tuples where the first element is the sort key and the second is the original string. That get sorted (first element in the tuples is used as sort key by default).

Then the outer list comprehension simply pulls the strings out of the sorted tuples.

3 Likes

#3

Or using a callback:
things = sorted(things, key = lambda s: int(s.split("_"))[1])

3 Likes

#4
 things = sorted(somelist, key=lambda x: int(x.split("_")[1]))
2 Likes

#5

0 Likes

#6

print(str[:8] + " " + str[8:len(str)]);

Python String Operations

0 Likes