【发布时间】:2021-06-02 16:40:44
【问题描述】:
我的目标是使用插入排序按第一列中的数字对 csv 文件的内容进行排序,例如我想要这样:
[[7831703, Christian, Schmidt]
[2299817, Amber, Cohen]
[1964394, Gregory, Hanson]
[1984288, Aaron, White]
[9713285, Alexander, Kirk]
[7025528, Janice, Lee]
[6441979, Sarah, Browning]
[8815776, Rick, Wallace]
[2395480, Martin, Weinstein]
[1927432, Stephen, Morrison]]
并将其排序为:
[[1927432, Stephen, Morrison]
[1964394, Gregory, Hanson]
[1984288, Aaron, White]
[2299817, Amber, Cohen]
[2395480, Martin, Weinstein]
[6441979, Sarah, Browning]
[7025528, Janice, Lee]
[7831703, Christian, Schmidt]
[8815776, Rick, Wallace]
[9713285, Alexander, Kirk]]
根据 python 中第一列中的数字,我当前的代码如下所示:
import csv
with open('EmployeeList.csv', newline='') as File:
reader = csv.reader(File)
readList = list(reader)
for row in reader:
print(row)
def insertionSort(readList):
#Traverse through 1 to the len of the list
for row in range(len(readList)):
# Traverse through 1 to len(arr)
for i in range(1, len(readList[row])):
key = readList[row][i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < readList[row][j] :
readList[row] = readList[row]
j -= 1
readList[row] = key
insertionSort(readList)
print ("Sorted array is:")
for i in range(len(readList)):
print ( readList[i])
代码已经可以对二维数组的内容进行排序,但它试图对所有内容进行排序。 我认为如果我摆脱了 [] 它会起作用,但在测试中它并没有给出我需要的东西。 为了再次澄清,我想根据第一列的数值对行位置进行排序。
【问题讨论】:
-
顺便说一句,代码的最后一部分你可以做
for x in readList: print (x)。您不需要像其他一些语言那样的索引。只需循环遍历可迭代对象的项目。那是更蟒蛇的方式。
标签: python csv sorting multidimensional-array insertion-sort