简体   繁体   English

是否可以通过数据对python中的csv文件进行排序?

[英]Is it possible to sort a csv file in python by data?

Is it possible to sort a csv file in python by an average, alphabetical order etc. Right now I have a simple print row code and am wondering if it's possible to sort the data. 是否可以按平均,字母顺序等对python中的csv文件进行排序。现在我有一个简单的打印行代码,想知道是否可以对数据进行排序。 (Name, class and score) It's for a task so I can't display my code here, so all answers are appreciated. (姓名,班级和分数)这是一项任务,因此我无法在此处显示我的代码,因此感谢所有答复。

If you are looking for sorting of a csv file based on columns, here is a quick solution: 如果要基于列对csv文件进行排序,这是一种快速解决方案:

import csv
import operator

# Sort based on 3 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("Sorted based on 3rd column")
print(sorted(r, key=operator.itemgetter(2), reverse=True))

# Sort based on 2 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("\nSorted based on 2nd column")
print(sorted(r, key=operator.itemgetter(1), reverse=True))

Suppose your csv is as mentioned below 假设您的csv如下所述

$> cat 1.csv 
1,a,32,hello
2,x,33,xello
3,h,23,belo
4,z,3,elo

Then when you run the above code: 然后,当您运行上面的代码时:

$> python ./sort.py
Sorted based on 3rd column
[['2', 'x', '33', 'xello'], ['1', 'a', '32', 'hello'], ['4', 'z', '3', 'elo'], ['3', 'h', '23', 'belo']]

Sorted based on 2nd column
[['4', 'z', '3', 'elo'], ['2', 'x', '33', 'xello'], ['3', 'h', '23', 'belo'], ['1', 'a', '32', 'hello']]

Is this what you were looking for? 这是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM