我有以下代码,并试图以最简单的方法对文件内容进行排序。
import csv
import operator
#==========Search by ID number. Return Just the Name Fields for the Student
with open("studentinfo.txt","r") as f:
studentfileReader=csv.reader(f)
id=input("Enter Id:")
for row in studentfileReader:
for field in row:
if field==id:
currentindex=row.index(id)
print(row[currentindex+1]+" "+row[currentindex+2])
#=========Sort by Last Name
with open("studentinfo.txt","r") as f:
studentfileReader=csv.reader(f)
sortedlist=sorted(f,key=operator.itemgetter(0),reverse=True)
print(sortedlist)我知道各种可能的解决方案,但不能完全让它们正常工作,而且为了教/学的目的,我也会对最简单有效的解决方案感兴趣,并有一个清晰的解释。
研究包括:*import运算符* sortedlist =排序(reader,key=operator.itemgetter(3),reverse=True)
或使用lambda sortedlist =sorted(读取器,key=lambda行: row3,reverse=True)
对于这个问题,我希望有人能发布一个完整的解决方案,按照姓氏和ID号进行排序,以举例说明两个不同的例子。对答案的扩展将显示如何在此特定示例中按多个值进行排序:
完整代码清单:
文件内容
002,Ash,Smith,Test1:20,Test2:20,Test3:100003
004,Grace,Asha,Test1:33,Test2:54,Test3:23
005,Cat,Zelch,Test1:66,Test2:22,Test3:11
001,Joe,Bloggs,Test1:99,Test2:100,Test3:1
003,Jonathan,Peter,Test1:99,Test2:33,Test3:44发布于 2017-07-20 17:42:40
使用导入操作符,就像您所做的那样,还有一个可能的解决方案:注意--理想情况下,您需要一个标头来区分您想要进行排序的内容(假设用户希望显式地指定这一点)
import csv
import operator
ifile =open('myfile.csv', 'rb')
infile = csv.reader(ifile)
# Note that if you have a header, this is the header line
infields = infile.next()
startindex = infields.index('Desired Header')
# Here you are creating the sorted list
sortedlist = sorted(infile, key=operator.itemgetter(startindex), reverse=True)
ifile.close
# open the output file - it can be the same as the input file
ofile = open('myoutput.csv, 'wb')
outfile.writerow(infields)
for row in sortedlist:
outfile.writerow(row)
ofile.close()发布于 2017-07-20 17:51:42
可以使用lambda函数对csv读取器返回的列表的任意键进行排序,例如,按姓氏排序(第三列):
with open("studentinfo.txt", "r") as f:
reader = csv.reader(f)
sorted_list = list(reader) # turn the reader iterator into a list
sorted_list.sort(key=lambda x: x[2]) # use the third column as a sorting key
print("\n".join(str(row) for row in sorted_list)) # prettier print或按ID (第一栏):
with open("studentinfo.txt", "r") as f:
reader = csv.reader(f)
sorted_list = list(reader) # turn the reader iterator into a list
sorted_list.sort(key=lambda x: x[0]) # the first column as a sorting key, can be omitted
print("\n".join(str(row) for row in sorted_list)) # prettier print或者用两把钥匙:
with open("studentinfo.txt", "r") as f:
reader = csv.reader(f)
sorted_list = list(reader) # turn the reader iterator into a list
sorted_list.sort(key=lambda x: (x[3], x[4])) # use fourth and fifth column
print("\n".join(str(row) for row in sorted_list)) # prettier print可以将reverse=True添加到下行排序的list.sort()调用中。
ADDENUM --如果您真的不想使用lambdas (为什么?),可以定义一个项-getter函数(或者只使用存在于此目的的operator.itemgetter )并将其传递给list.sort()调用,例如:
def get_third_column(x):
return x[2]
with open("studentinfo.txt", "r") as f:
reader = csv.reader(f)
sorted_list = list(reader) # turn the reader iterator into a list
sorted_list.sort(key=get_third_column) # use the third column as a sorting key
print("\n".join(str(row) for row in sorted_list)) # prettier print发布于 2017-07-20 17:54:32
一种简洁、简单的读取->排序->的解决方案:
import csv
import operator
with open("input.csv") as fh:
reader = csv.reader(fh)
rows = sorted(reader, key=operator.itemgetter(0), reverse=True)
with open("output.csv", "w") as fh:
csv.writer(fh).writerows(rows)要在控制台上打印而不是写入文件,可以使用sys.stdout作为文件句柄:
import sys
with sys.stdout as fh:
csv.writer(fh).writerows(rows)operator.itemgetter(0)确定要按哪个字段进行排序。第0字段是id.若要按姓氏进行排序,请使用operator.itemgetter(2),因为姓氏是第三列。
若要按多个字段进行排序,您需要使用lambda,例如,按最后一次排序,然后按名称排序:
rows = sorted(reader, key=lambda x: (x[2], x[1]), reverse=True)排序之前的代码(您要求用户输入Id )也可以改进:
id在Python中隐藏内置函数,因此不建议将其用作变量。你可以这样写:
with open("studentinfo.txt") as fh:
reader = csv.reader(fh)
student_id = input("Enter Id:")
for row in reader:
if row[0] == student_id:
print(row[1] + " " + row[2])https://stackoverflow.com/questions/45221637
复制相似问题