在csv文件中输入用户的名称及其测验得分。我想按字母顺序对用户名称进行排序,但我不知道如何执行此操作。提前致谢。以下是我的代码片段。
userName=input('Please enter your full name: ').title()
newrecord = "{user_name},{score_1},{score_2},{score_3}\n".format(user_name=userName, score_1=quiz_scores[0], score_2=quiz_scores[1], score_3=quiz_scores[2])
classa = input("What class are you in? ")
if classa =='1':
file=open('classroom1.csv', "a+")
file.write(newrecord)
file.close()
with open('classroom1.csv') as csvfile:
readCSV = csv.reader(csvfile)
答案 0 :(得分:0)
我假设给定一个用户名和测验分数的csv文件,您想要读取csv文件,然后根据用户名进行排序。您的问题(我相信)是每次从csv文件中读取时,都会得到[user_name, score1, score2, score3]
形式的列表。
如果是这样,为什么不将每个这样的列表存储在字典中,使用user_names作为键,然后对字典键进行排序 - 即
sorting_dict = {}
for curr_elem in readCSV:
sorting_dict[curr_elem[0]] = curr_elem #Note this assumes no 2 users have the same name
sorted_names = sorted(sorting_dict.keys()) # actually sorted(sorting_dict) will also work and may be preferred, but '.keys()' makes it clearer for me
现在,您可以按排序顺序访问记录:
for curr_user in sorted_names:
curr_record = sorting_dict[curr_user]
#Do what you want from here...
=============================================== =====
嗯......奇怪的是,这对你不起作用。我制作了一个像你描述的虚拟文件,这似乎对我有用:>>> f=open('csv.txt','r')
>>> readCSV = csv.reader(f)
>>> for curr_elem in readCSV:
... sorting_dict[curr_elem[0]] = curr_elem
...
>>> sorted_names = sorted(sorting_dict.keys())
>>> sorted_names
['art', 'bob', 'dick', 'harry', 'tom']
>>> for curr_user in sorted_names:
... print sorting_dict[curr_user]
...
['art', '77', '99', '98']
['bob', ' 88', '99', '78']
['dick', '77', '66', '99']
['harry', '90', '78', '98']
['tom', '33', '98', '67']
>>>
我的csv.txt文件是:
bob, 88,99,78
art,77,99,98
tom,33,98,67
dick,77,66,99
harry,90,78,98
这里唯一的“陷阱”是你需要确保'harry'行不以\n
结束,否则csv阅读器将读取一个空行,该行将在{{1但是,人们可以很容易地防范这一点。
答案 1 :(得分:0)
考虑使用list.sort()
函数,方法是将csv数据附加到列表中,然后使用定义的函数按first element对其进行排序。这个函数甚至可能是不必要的,因为Python默认为嵌套列表中的第一个元素,因此可以省略key
参数:
csvdata = []
with open('classroom1.csv') as csvfile:
readCSV = csv.reader(csvfile)
for line in readCSV:
csvdata.append(line)
for i in csvdata:
print(i)
#['bravo', '93']
#['alpha', '86']
#['charlie', '67']
#['echo', '70']
#['delta', '75']
def getKey(item):
return item[0]
csvdata.sort(key=getKey)
for i in csvdata:
print(i)
#['alpha', '86']
#['bravo', '93']
#['charlie', '67']
#['delta', '75']
#['echo', '70']
答案 2 :(得分:0)
为什么不使用熊猫?
df = pd.read_csv('classroom1.csv', sep = ',', names = ['user_name','score_1','score_2','score_3'])
df = df.sort('user_name')
df.to_csv('classroom1.csv', index = False, header = False)
应该照顾它。