Python按对象排序

Python按对象排序,python,python-3.x,Python,Python 3.x,在PYTHON中如何按名称和年龄排序? 我在.txt文件中有以下列表: John, 14 Mike, 18 Marco, 25 Michael, 33 我想按姓名和年龄来分类。我写了这段代码,但不起作用: file = open("people.txt", "r") data = file.readlines() i = 0 for line in data: name, age = line.split(',') list = [name, age] i +=

在PYTHON中如何按名称和年龄排序? 我在.txt文件中有以下列表:

John, 14
Mike, 18
Marco, 25
Michael, 33
我想按姓名和年龄来分类。我写了这段代码,但不起作用:

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])
非常感谢各位:)

这里有一种方法:

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])
使用:

  • 处理自动文件关闭的上下文管理器(这是带有的
  • f中的
    for line
    迭代器一次循环一行文件
  • 根据需要将行拆分为列表的列表理解
  • int
    而不是
    eval
  • 将所有
    line.name
    引用更改为
    line[0]
    ——如果需要
    .name
    访问,可以将这些行设置为适当的类(或
    namedtuple
    s)

不过,一般来说,解析csv文件的解决方案是存在的(例如,您的代码中还有一些问题。

wow。我认为您应该首先修复缩进。这种情况下,
eval
应该被发音为
邪恶
可能的重复