我一直在处理这段代码(在python中)打印一个CSV文件,已排序。第一个选择工作正常,并按字母顺序排序。但是,选择2部分应该将csv文件排序为最高分。 text / csv文件(
name, score, out of:
Ben,5,20
James,6,20
Adam,12,20
Will,20,20
代码:
import operator
import csv
file = open("scores.txt", "r")
scores = csv.reader(file, delimiter=",")
sort = sorted(scores)
for i in range(0, len(sort)):
sort[i].append((max(sort[i][1:2])))
#Alphabetical Order
choice = input("Choice: ")
if choice == "1":
sort = list(sorted(sort,key = operator.itemgetter(0), reverse=False))
print("\nAlphabetical Order:")
print("===================")
for i in range(0, len(sort)):
print("Name: ", sort[i][0], "\tScore: ", sort[i][1])
#Highest score
#sort = sorted(scores)
elif choice == "2":
print("\nHigh Scores:")
print("============")
sort = list(sorted(sort,key = operator.itemgetter(1, 2),reverse=True))
for i in range(0, len(sort)):
print("Name:", sort[i][0], "\tScore:", sort[i][1], "Out of", sort[i][2])
答案 0 :(得分:0)
首先:
max(sort[i][1:2])
将仅返回数字对中的第一个,因为切片返回元素1
到2-1
。
您可以将其更改为
max(sort[i][1:3])
但是,与.csv文件中的数字对应的字段是字符串(因为它们是从csv.reader
返回的)。您应该考虑在排序时将它们转换为整数。不使用operator
东西的简单方法是使用匿名函数将字符串对映射到整数元组:
sort = sorted(sort, key = lambda x: (int(x[1]), int(x[2])), reverse = True)
# no need to put the rvalue in list()
使用与您的数字对对应的整数元组作为键。此外,如果您使用python 2.x
,则应切换到raw_input
或使用input
并使用str(choice)
,如BigBang的答案所示。
要了解为什么在根据数字对进行排序时您的键选择不起作用,请记住,数字对是从字符串列表中的csv.reader返回的(例如['Name','12',' 20' ])。很容易看出:
>>> ('12', '20') > ('6', '20')
False
此比较不符合12 > 6
的情况,因为字符串按字典顺序进行比较。这里,'1'小于'6'。
答案 1 :(得分:0)
如果第一部分有效,那么显然你使用的是python3,你只需要按照字母顺序对分数进行排序,因为名字首先出现。要按分数排序,您需要将其转换为int。
with open("scores.txt") as f:
headers = next(f)# skip header
scores = list(csv.reader(f, delimiter=","))
inp = input("Choose 1 for alpha sort or 2 for highscore sort")
if inp == "1":
print("\nAlphabetical Order:")
scores.sort()
for name,score,out in scores:
print("Name: {} score: {} out of {}".format(name,score,out))
elif inp == "2":
print("\nHigh Scores:")
print("============")
scores.sort(key=lambda x:int(x[1]),reverse=True)
for name,score,out in scores:
print("Name: {} score: {} out of {}".format(name,score,out))
输出:
Alphabetical Order:
===================
Name: Adam score: 12 out of 20
Name: Ben score: 5 out of 20
Name: James score: 6 out of 20
Name: Will score: 20 out of 20
High Scores:
============
Name: Will score: 20 out of 20
Name: Adam score: 12 out of 20
Name: James score: 6 out of 20
Name: Ben score: 5 out of 20
答案 2 :(得分:-1)
你的选择"是整数,你将它与字符串进行比较,所以正确的比较将是:
if str(choice) == "1":
#do something
elif str(choice) == "2":
#do something