此外,如果我想按年龄排序,我怎么能这样做? 我尝试了myFile.sort(),但它崩溃了代码说 “对象没有属性'排序'”
fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "
myFile = open(fileName, ACCESSMODE)
nbrGuest = input("How many guests do you have? ")
for index in range (int(nbrGuest)) :
name = input("Enter guest name: " ).capitalize()
age = input("Enter guest age: " )
myFile.write(name + "," + age + "\n")
myFile.close()
答案 0 :(得分:1)
因此代码现在分为两部分。
java.exe -classpath E:\lib\* Main
第一部分获取用户输入并将所有信息存储在元组列表中。每个fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "
nbrGuest = input("How many guests do you have? ")
guest_list = []
for index in range(int(nbrGuest)):
name = input("Enter guest name:\t").capitalize()
age = input("Enter guest age:\t")
guest_list.append((name, age))
guest_list.sort(key=lambda x: x[1])
with open(fileName, ACCESSMODE) as myFile:
for guest in guest_list:
myFile.write(guest[0] + "," + guest[1] + "\n")
看起来都像tuple
。在访客列表完成后,根据访客年龄(最年轻的第一个)使用('ALEX', '24')
方法对其进行排序,使用.sort()
来撤销订单)。最后,排序的名称和年龄将写入由,reverse=True
语句管理的文件,这样您就不必担心关闭它或刷新它。
答案 1 :(得分:-1)
重复问题:sort-csv-by-column
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use lambda
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
请注意,只会对变量中的列表进行排序,而不是文件。您将首先对列表进行排序,然后再次写入该文件。