首页 > 解决方案 > 将从csv读取的多列数据排序到Python3列表中不起作用

问题描述

我正在尝试使用如下所示的数据对包含数据的文件进行排序:

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

我已经将我的数据转换为 int 数据类型以避免 alpha 排序,但我认为我仍然缺少一些东西。我相信列表是可变的,因此假设列表列表也是可变的。

另外,我将如何按多列对其进行排序:

combined_list = sorted(combined_list, key = operator.itemgetter(1))

最后,我仍在学习在我的编码中使用 Pythonic,所以任何提示都会受到赞赏。

谢谢

标签: pythonpython-3.xlistcsvsorting

解决方案


推荐阅读