-1

How can I sort by name and age in PYTHON? I have the following list in .txt file:

John, 14
Mike, 18
Marco, 25
Michael, 33

I want to sort this by name and by age. I wrote this code but it doesn't work:

file = open("people.txt", "r")
data = file.readlines()
i = 0
for line in data:
     name, age = line.split(',')
     list = [name, age]
     i += 1
     print("For sorting by name press (1);")
     print("For sorting by age press (2);")
     z = eval(input())
     if z == 1:
          list.sort(key=lambda x: x.name, reverse=True)
          print([item.name for item in list])

Thank you very much guys :)

Aaron_ab
  • 3,126
  • 3
  • 26
  • 40

1 Answers1

0

Here's one approach:

with open("so.txt", "r") as f:
    lines = [line.split(',') for line in f]

    print("For sorting by name press (1);")
    print("For sorting by age press (2);")

    z = int(input())
    if z == 1:
        lines.sort(key=lambda x: x[0], reverse=True)
        print([item[0] for item in lines])

Using:

  • a context manager to handle automatic file closure (this is the with)
  • the for line in f iterator to loop over the file's lines one at a time
  • a list comprehension to split the lines into lists as needed
  • int instead of eval
  • changing all line.name references to line[0] -- you could make the lines proper classes (or namedtuples if you wanted the .name access.

Though, in general, solutions for parsing csv files exist (e.g. csv -- there were a few more issues in your code than just that.

jedwards
  • 28,237
  • 3
  • 59
  • 86