我有一個 csv 檔案,其中包含地區、政黨、選票、州和年份行。我只想從 2018 年開始對德克薩斯州從最低票數到最高民主票數的每個地區進行排名,我怎樣才能在最初學者的代碼中實作這一點?我必須使用選擇/插入排序嗎?
uj5u.com熱心網友回復:
如果您要使用 Java 執行此操作(不確定它對初學者有多友好),您可以執行類似的操作
String s = Files.readString(pathToYourFile);
然后將字串拆分為字串陣列,由換行符“\n”劃定。
然后你可以將字串決議成一個物件,用字符“,”來描述,因為它是 csv。現在您可以創建一個串列,然后執行 Collections.sort(yourList)。
或者,您可以使用 SQL 資料庫 :)
uj5u.com熱心網友回復:
這就是我對它的個性:
with open('data.csv') as f:
file_content = f.read()
data = [line.split(';') for line in file_content.splitlines()]
sorted_data = sorted(data, key=lambda x: int(x[1]), reverse=True)
print('\n'.join(';'.join(x) for x in sorted_data))
uj5u.com熱心網友回復:
我會使用冒泡排序,它是最簡單的數字排序演算法。
def bubble_sort(your_list):
has_swapped = True
index_of_votes_value = 0 #assuming the list is 2D, each year, and then within the year, the votes, party, etc.
num_of_iterations = 0
while(has_swapped):
has_swapped = False
for i in range(len(your_list) - num_of_iterations - 1):
if your_list[i][index_of_votes_value] > your_list[i 1][index_of_votes_value]:
# Swap
your_list[i][index_of_votes_value], your_list[i 1][index_of_votes_value] = your_list[i 1][index_of_votes_value], your_list[i][index_of_votes_value]
has_swapped = True
num_of_iterations = 1
該演算法遍歷您的串列,它檢查每個索引是否大于其后的索引,如果是,則交換它們。它不斷地遍歷串列,直到串列有序為止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490917.html
上一篇:將串列中的序列化位連接成位元組
