Python 按特定列对CSV进行BubbleSort
我有一个包含多行和列的csv文件。 我想使用python和bubblesort按特定列对文件进行排序。 例如: 输入csv文件: 输出: 在本例中,应按第三列对行进行排序Python 按特定列对CSV进行BubbleSort,python,bubble-sort,Python,Bubble Sort,我有一个包含多行和列的csv文件。 我想使用python和bubblesort按特定列对文件进行排序。 例如: 输入csv文件: 输出: 在本例中,应按第三列对行进行排序 到目前为止,我只能对第三列进行排序,但其他列保持不变。这里是一个使用python内置csv模块的实现。此解决方案假定输入csv文件位于test.csv中,并且您希望输出位于output.csv中 import csv file = csv.reader(open('test.csv', 'r')) rows = [row fo
到目前为止,我只能对第三列进行排序,但其他列保持不变。这里是一个使用python内置csv模块的实现。此解决方案假定输入csv文件位于test.csv中,并且您希望输出位于output.csv中
import csv
file = csv.reader(open('test.csv', 'r'))
rows = [row for row in file]
# Python program for implementation of Bubble Sort
# from: https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# modified to sort by the third element in the row per SO question
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n - i - 1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j][2] > arr[j + 1][2]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
sorted_rows = [', '.join(row)+'\n' for row in bubble_sort(rows)]
with open('output.csv', 'w+') as f:
f.writelines(sorted_rows)
注意:您还可以使用pandas读取csv文件,并使用pandas中更快的内置算法进行排序 嗨!欢迎来到Seack Overflow。请参阅和如何创建:如果不共享代码,很难帮助修复代码(尽管下面有一位非常慷慨的用户编写了完整的实现)。。。
Dave,Chicago,12345,Hiking
Daniel,New York,23456,Gaming
Ross,Boston,34567,Chess
Melinda,Washington,45678,Sports
import csv
file = csv.reader(open('test.csv', 'r'))
rows = [row for row in file]
# Python program for implementation of Bubble Sort
# from: https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# modified to sort by the third element in the row per SO question
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n - i - 1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j][2] > arr[j + 1][2]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
sorted_rows = [', '.join(row)+'\n' for row in bubble_sort(rows)]
with open('output.csv', 'w+') as f:
f.writelines(sorted_rows)