我有一個從文本檔案中獲取的陣列,在陣列中是:
[('Sammy', '[email protected]', '72'), ('John', '[email protected]', '33'), ('Felix', '[email protected]', '89'), ('Henry', '[email protected]', '23'), ('Steven', '[email protected]', '83'), ('Harry', '[email protected]', '46'), ('Billy', '[email protected]', '62'), ('Alex', '[email protected]', '66'), ('Finn', '[email protected]', '49')]
在這個二維陣列中,我想對串列頂部得分最高的資料和串列底部得分最低的資料進行排序。該串列稱為 sorted_database 并且在下面
我的冒泡排序不起作用的代碼如下(我也想在不使用任何函式的情況下長期進行,例如.sort):
swapped_database = []
def sortdata():
swapped = True
length = len(database)
print(length)
temp = 0
while swapped == True:
swapped = False
for index in range(0,length -1,3):
print(index)
if database[index] > database[index 1]:
temp = database[index]
database[index] = database[index 1]
database[index 1] = temp
swapped = True
swapped_database.append(database)
print(swapped_database)
sortdata()
提前致謝
uj5u.com熱心網友回復:
有以下問題:
內部回圈不應步長為 3。元組大小與該元組在
database串列中所在的索引無關。值database[index]是一個元組,而不是元組的成員。應該在分數上進行比較。這意味著您應該明確比較元組的第三個元素,并將它們轉換為數字——因為它們是字串。
swapped_database在這里沒有任何作用。冒泡排序是一種就地排序演算法,因此它使database自己排序。而且,swapped_database.append(database)意義不大。它database在里面做一個條目swapped_database
關于代碼的其他一些說明:
避免改變全域變數,所以
database作為引數傳遞給你的函式。在 Python 中,您不需要
temp變數來交換值。改用元組賦值。while swapped == True是矯枉過正,因為swapped已經是一個布林值,所以就這樣做while swapped
def sortdata(database):
swapped = True
length = len(database)
while swapped == True:
swapped = False
for index in range(0,length -1):
if int(database[index][2]) < int(database[index 1][2]):
database[index], database[index 1] = database[index 1], database[index]
swapped = True
示例使用:
sortdata(database)
for entry in database:
print(entry)
uj5u.com熱心網友回復:
這種方法對于swappedboolean 和 step by看起來過于復雜3。您可以簡單地使用雙for回圈。
這是一個回傳排序串列的作業實作。它使用兩個for回圈進行交換,并根據每個元組中第三個元素的整數值比較值(而不是直接進行元組比較):
def sortdata(database):
for iter_idx in range(len(database)):
for elem_idx in range(len(database) - iter_idx - 1):
if int(database[elem_idx][2]) > int(database[elem_idx 1][2]):
database[elem_idx], database[elem_idx 1] = \
database[elem_idx 1], database[elem_idx]
return database
使用示例資料,呼叫print(sortdata(database))輸出:
[[('John', '[email protected]', '33'),
('Sammy', '[email protected]', '72'),
('Felix', '[email protected]', '89'),
('Henry', '[email protected]', '23'),
('Steven', '[email protected]', '83'),
('Harry', '[email protected]', '46'),
('Billy', '[email protected]', '62'),
('Alex', '[email protected]', '66'),
('Finn', '[email protected]', '49')]]
確保您database作為引數傳遞給函式。for第二個回圈的上限是Mushroomatoriter_idx建議的優化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448628.html
