我正在尝试对包含数据的文件进行排序,数据如下:
col_a,col_b,col_c
100,100,100
10,0,0
20,30,30
70,20,80
22,88,45
37,18,73
60,72,6
15,18,56
71,67,78
93,48,74
4,93,73
我希望排序按第一列降序,如果第一列和第二列之间有任何关联,则按第二列降序,如果仍有任何关联需要处理,则按相同的降序方式按第三列降序。
完成三列排序后,应按此顺序对数据进行排序:
100,45,35
87,74,91
71,84,52
70,6,97
70,2,80
5,55,83
5,55,5
这是我的程序:
import csv
import operator
#create an empty list
combined_list = []
#read list of tests from test profile file
with open("data_file.csv") as input_file:
reader = csv.reader(input_file)
header = next(reader) #there is a header row, which I'm ignoring
a_row_list = [[int(row[0]),int(row[1]),int(row[2])] for row in reader]
#add each row read in to the new list
combined_list.append(a_row_list)
#show its type
print(type(combined_list))
#print records
print("1: Read in")
for row in combined_list:
print(row)
#sorted method #1
combined_list = sorted(combined_list, key = operator.itemgetter(1))
print("2: First sort")
for row in combined_list:
print(row)
#sorted method #2
combined_list = sorted(combined_list, key=lambda x: (x[0], x[1], x[2]))
print("3: Second sort")
for row in combined_list:
print(row)
#sorted method #3
combined_list.sort(key = lambda ele : ele[0],ele[1],ele[2])
print("4: Third sort")
for row in combined_list:
print(row)
$python3 TestSort.py
<class 'list'>
1: Read in
[[100, 45, 35], [5, 55, 5], [5, 55, 83], [70, 2, 80], [70, 6, 97], [87, 74, 91], [71, 84, 52]]
2: First sort
[[100, 45, 35], [5, 55, 5], [5, 55, 83], [70, 2, 80], [70, 6, 97], [87, 74, 91], [71, 84, 52]]
3: Second sort
[[100, 45, 35], [5, 55, 5], [5, 55, 83], [70, 2, 80], [70, 6, 97], [87, 74, 91], [71, 84, 52]]
4: Third sort
[[100, 45, 35], [5, 55, 5], [5, 55, 83], [70, 2, 80], [70, 6, 97], [87, 74, 91], [71, 84, 52]]
你可以看到这三个输出看起来都是原来的,我想这意味着排序不起作用。
以下是一些环境信息:
python3 --version
Python 3.6.5 :: Anaconda, Inc.
sw_vers
ProductName: Mac OS X
ProductVersion: 10.13.6
BuildVersion: 17G2208
另外,如何按多个列对其排序:
combined_list = sorted(combined_list, key = operator.itemgetter(1))
最后,我仍在学习在我的编码蟒蛇,所以任何提示将不胜感激。
谢谢你