2

So a while ago I asked this question here: Sorting lists in python

I have this code here:

def sort(names, rank):
    lst=[]
    for x in range(0, len(names)):
        lst.append((int(rank[x]), names[x]))
    lst.sort(key=lambda x: (-x[0],len(x[1])) )
    newArr = []
    for z in range(0, len(lst)):
        row = lst[z]
        newArr.append(row[1] + " " + str(row[0]))
    return newArr

But I also need to sort name more, if the length of the names are the same I need the one with the capital letter to come first. Any ideas?

Community
  • 1
  • 1
FabianCook
  • 20,269
  • 16
  • 67
  • 115

1 Answers1

1

Add another entry into the tuple for the third condition.

def sort(names, rank):
    lst=[]
    for x in range(0, len(names)):
        lst.append((int(rank[x]), names[x]))
    lst.sort(key=lambda x: (-x[0],len(x[1]), ord(x[1][0])) )
    newArr = []
    for z in range(0, len(lst)):
        row = lst[z]
        newArr.append(row[1] + " " + str(row[0]))
    return newArr

I rewrote your code, making some style changes:

def sort(names, rank):
    lst=[]
    for index, name in enumerate(names):
        lst.append((int(rank[index]), name))
    lst.sort(key=lambda x: (-x[0],len(x[1]),  ord(x[1][0])))
    output = []
    for row in lst:
        output.append(row[1] + " " + str(row[0]))
    return output

I personally find the second approach to be a little more readable.

Brenden Brown
  • 3,125
  • 1
  • 14
  • 15