如何在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])
非常感谢你们:)
答案 0 :(得分:0)
这是一种方法:
message Person {
string address = 2;
reserved 1;
}
使用:
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])
)with
迭代器一次遍历文件行for line in f
而非int
eval
的引用更改为line.name
-您可以将各行设置为适当的类(如果需要line[0]
,则可以将这些行设置为namedtuple
。尽管总的来说,存在用于解析csv文件的解决方案(例如csv
-您的代码中存在的问题不止于此。