0

I'm trying to sort a list consisting of names and numbers, in this case a persons name and their bowling score. I want to sort the list alphabetically and numerically. I'm having a hard time figuring out how to sort the list numerically. The list looks like this: ['', 'Ann, 40', 'Jeff, 250', 'Zane, 20']. Is there anyway I can use the built in sort function for the second element in the list rather than the first?

#Here is the code
l=['Ann, 40', 'Jeff, 250', 'Zane, 20']


l.sort(l[1])
for i in l:
    print(i)
#l.sort(l[1]) does not work

The end goal will be to display

Jeff, 250
Ann, 40
Zane, 20
blhsing
  • 91,368
  • 6
  • 71
  • 106
cupcake
  • 11
  • 2

3 Answers3

4

You can sort in reverse order with a key function that splits each input string by , and returns the second item after converting it to an integer:

l.sort(key=lambda s: int(s.split(', ')[1]), reverse=True)

l becomes:

['Jeff, 250', 'Ann, 40', 'Zane, 20']
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Split the list and sort on the second element after converting it to a list

l=['Ann, 40', 'Jeff, 250', 'Zane, 20']
l.sort(key = lambda x: int(x.split()[1]), reverse=True)
for item in l:
    print(item)
#Jeff, 250
#Ann, 40
#Zane, 20
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

For my a cleaner way to do that will be:

First create a class to handle your objects and then implement the methods needed for sorting, gt and lt.

@dataclass
class Person:

    name: str
    value: int

    @classmethod
    def create_from_str(cls, string):
        name, value = string.split(", ")
        return cls(name, int(value))

    def __gt__(self, other):
        return self.value > other.value

    def __lt__(self, other):
        return self.value < other.value

    def __repr__(self):
        return f"{self.name}, {self.value}"


l = ['Ann, 40', 'Jeff, 250', 'Zane, 20']

persons = [Person.create_from_str(string) for string in l]

persons.sort(reverse=True)

print("\n".join(map(str, persons)))

# Jeff, 250
# Ann, 40
# Zane, 20
Daniel Albarral
  • 412
  • 5
  • 12