我有一個名為sample.csv的csv檔案,我把它轉換成了一條記錄,這條記錄被設定為一個字串值和一個整數值,像這樣:
[Name,10]
[Name1,12]
[Name2,14] 。
我希望能夠將這些記錄按降序排序,然后最終列印出三個得分最高的學生的名字和分數,以及得分最低的學生的名字和分數。以下是我目前的代碼,我無法按整數值對記錄進行排序。
import csv
file = open("sample.csv"/span>)
csvreader = csv.reader(file)
rows = []
for row in csvreader:
rows.append(row)
file.close()
sortedFile=[]
sortedFile=sorted(rows, key=lambda rows: rows[1] )
print(sortedFile)
編輯:
一個非常有幫助的人發表了評論,但現在不管怎樣,他們已經洗掉了他們的評論。
import csv
file = open("sample.csv"/span>)
csvreader = csv.reader(file)
rows = []
for row in csvreader:
rows.append(row)
file.close()
sortedFile=[]
sortedFile=sorted(rows, key=lambda rows: int(rows[1]) [::-1]
print(sortedFile[0])
print(sortedFile[1])
print(sortedFile[2])
print(sortedFile[-1] )
我的代碼現在看起來是這樣的,我已經快完成了,我相信我錯過了一些非常簡單的東西,我所希望的是在陣列附近有一些文字說
"得分最高的人是", (name[0]),"with a score of, (score[0])
"得分最高的人是",(name[1]),"有個分數,(score[1] )
"得分最高的人是", (name[2]),"with a score of,(score[2] )
"得分最低的人是",(name[-1]),"得分為,(score[-1] )
uj5u.com熱心網友回復:
也許可以這樣:
sortedFile = sorted(rows, key=lambda rows: int(rows[1] )?
uj5u.com熱心網友回復:
假設你的資料是在一個串列中,你可以呼叫sort,用key引數來指定如何對串列進行排序。在這種情況下,你可以使用負值-x[1]來對其進行反向排序。
data = [['Name'/span>,10]。
['Name1',12] 。
['Name2',14 ]]
data.sort(key = lambda x: -x[1] )
結果:
[['Name2', 14] 。['Name1', 12], ['姓名', 10]]
uj5u.com熱心網友回復:
我建議做如下修改:
with來打開檔案;reverse=True的可選關鍵字引數到sorted;zip來迭代并列印第一、第二、第三和最后的分數。import csv
with open("sample.csv"/span>, 'r'/span>) 作為檔案。
csvreader = csv.reader(file)
sortedFile = sorted(csvreader, key=lambda rows: int(rows[1]), reverse=True)
print(sortedFile)
for (i,place) in zip([0, 1,2, -1], ['最高', '第二高', '第三高', '最低'])。)
print('擁有{}分數的人是{},得分是{}。'。 format(place, sortedFile[i][0], sortedFile[i][1] )
示例輸入 sample.csv
Alice,12
Max,11
Medhi,18
陳,17
薩沙,15。
輸出示例
[['Medhi', '18'], ['陳', '17'], ['Sasha', '15'], ['Alice', '12'], ['Max', '11'] ]
得分最高的人是梅迪,分數為18。
得分第二高的人是陳,得分17.。
得分第三高的人是Sasha ,得分15.。
得分最低的人是Max,得分11.。
uj5u.com熱心網友回復:
你在你的代碼中以升序排序,從條件來看,有必要以降序排序。
嘗試這個選項:
代碼:
rows=[['A',10]。
['B',12]。
['C',11]]
sortedFile=sorted(rows, key=lambda rows: int(rows[1]) [::-1]
if len(sortedFile) > 1:
print(sortedFile)
for i in range(len(sortedFile) - 1) 。
print(sortedFile[i])
print(sortedFile[-1])
elif len(sortedFile) == 1:
print(sortedFile)
print(sortedFile[0])
else:
print('list is empty')
這段代碼考慮到了3個條件。如果串列長度大于1,則等于1,等于0。
這段代碼考慮了3個條件。
為了獲得漂亮的輸出,你可以使用f-strings,也就是說,比如說,像這樣:
print(f'The person with the highest score is {name[0>}, 分數為{score[0]}')
我將通過我自己的例子來告訴你:
if len(sortedFile) > 1:
for i in range(len(sortedFile) - 1) 。
print(f'The person with the highest score is {sortedFile[i][0]}。分數為{sortedFile[i][1]}')
print(f'The person with the highest score is {sortedFile[-1] [0]}。分數為{sortedFile[-1][1]}' )
elif len(sortedFile) == 1:
print(f'The person with the highest score is {sortedFile[0] [0]}, 分數為{sortedFile[0][1]}' )
else:
print('list is empty')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/328360.html
標籤:
