我開始了 100 天的代碼,這個專案是無聲拍賣(第 9 天)。您獲取用戶的姓名和投標價格,將其存盤在字典中,然后將其清除(提示查看是否有其他用戶)。重點是收集鍵/值(未知)并對它們進行排序,以便列印最高值(投標人)。
由于我不知道字典中的鍵或值是什么,我想在“否”提示后對字典進行排序。然后我決定將字典轉換為串列,以便我可以分別訪問鍵和值。我需要這樣做的原因是因為在列印陳述句中,我在句子的不同部分列印了名稱(鍵)和投標價格(值)。
示例輸入:
{'alan': '115', 'jay': '125', 'alex': '155'} ['alan', 'jay', 'alex'] ['115', '125', '155']
輸出:獲勝者是 alex,出價 155 美元。
當用戶輸入 $5 作為輸入時,我遇到了錯誤:
{'john': '105', 'alex': '115', 'jae': '5'} ['john', 'alex', 'jae'] ['105', '115', '5']
獲勝者是 jae,出價 5 美元。
關于 key_list 和 key_value 的另一個錯誤“分配前參考的區域變數”。我讀到的解決方案是在函式的開頭寫全域。
from replit import clear
from operator import itemgetter
#HINT: You can call clear() to clear the output in the console.
from art import logo
print(logo)
bid_dictionary = {}
def main():
global key_list
global value_list
name = input("What is your name? ")
bid_price = input("What is your bid price? ")
bid_dictionary[name] = bid_price
other_users = input("Are there other users who want to bid? Enter Yes or No. ").lower()
if other_users == "yes":
clear()
main()
elif other_users == "no":
clear()
list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: item[1]))
key_list = list(list_sorted.keys())
value_list = list(list_sorted.values())
print(list_sorted, key_list, value_list)
print(f"The winner is {key_list[-1]} with a bid of ${value_list[-1]}.")
main()
uj5u.com熱心網友回復:
list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: item[1]))
您在這里將價格排序為字串(item[1]
是字串)。“5”在字典順序方面排在最后(如何比較字串)。
在比較之前,您需要將價格轉換為整數
嘗試這個:
list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: int(item[1])))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504904.html