0

Below is my code and i am trying to sort the tuple with respect to 2nd element.

list = ["abc14_90","abc44_88","abc14_89"]
listLength = len(list)
for i in range(0,listLength):
    tempList = list[i].split('_')
    tempList1 = tempList[0].split('c')
    if(i==0):
        tupleNumber = [(list[i], int(tempList1[1]),int(tempList[1]))]
    else:
        tupleNumber = tupleNumber + [(list[i], int(tempList1[1]),int(tempList[1]))]

print (tupleNumber)

sorted(tupleNumber, key=lambda x: x[2])

print (tupleNumber)

Expected Output:

[ ('abc44_88', 44, 88), ('abc14_89', 14, 89),('abc14_90', 14, 90),]

Output Observed:

[('abc14_90', 14, 90), ('abc44_88', 44, 88), ('abc14_89', 14, 89)]

Basically the sort seems to have no effect.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
moooni moon
  • 333
  • 1
  • 5
  • 19

2 Answers2

0

sorted() doesn't sort in place but it returns a sorted list, so you need to reassign the list to tupleNumber as the following:

print (tupleNumber)

tupleNumber = sorted(tupleNumber, key=lambda x: x[2])

print (tupleNumber)
Mohd
  • 5,523
  • 7
  • 19
  • 30
-1

You can try this:

import re
import itertools
l = ["abc14_90","abc44_88","abc14_89"]
new_l = [tuple(itertools.chain.from_iterable([[i], map(int, re.findall("\d+", i))])) for i in sorted(l, key=lambda x: int(x[-2:]))]

Output:

[('abc44_88', 44, 88), ('abc14_89', 14, 89), ('abc14_90', 14, 90)]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102