簡體   English   中英

python 字典中的循環問題

[英]Problem with loops in python dictionaries

我是 python 的新手,所以也許我的問題很容易解決。

我很難理解字典以及如何只獲取我想要比較的數字(整數)。 我在谷歌上搜索了 8 個小時,我的頭有點痛。

我得到的錯誤: TypeError: '>' not supported between instances of 'list' and 'int'

這是我的代碼:

dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

highest_price = 0
winner = ""

for value in dictionary1:
    bid_amount = dictionary1["price"]
    if bid_amount > highest_price:
        highest_price = bid_amount
        winner = name1[name]

print(f"the winner is: {winner}. With {highest_price}")

技術問題

for循環中的第一行不會返回一個價格 integer,而是返回整個價目表。 這個dictionary1["price"]給你[55, 100, 25]

邏輯問題

數據結構

我認為您誤解了字典的工作原理。 在您的情況下,最好使用具有價格是值而名稱是鍵的結構的字典。

better_dict = {
    'a': 55,
    'b': 100,
    'c': 25}

在下面的解決方案代碼中,我通過dict(zip(...))將您的字典轉換為該形式。

遍歷字典

當您使用for循環遍歷字典時,您只會得到鍵而不是值。 在我的示例中,您有鍵['a', 'b', 'c'] 當你想訪問字典中的值時,你必須在循環中使用鍵。

解決方案

此解決方案嘗試盡可能少地修改您的代碼。

#!/usr/bin/python3
dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

# transform your dict into an easier structure
better_dict = dict(zip(dictionary1["name"], dictionary1["price"]))
# result --> {'a': 55, 'b': 100, 'c': 25}

highest_price = 0
winner = ""

for name in better_dict:  # --> ['a', 'b', 'c']
    # get the value by key/name
    bid_amount = better_dict[name]
    if bid_amount > highest_price:
        highest_price = bid_amount
        winner = name  # use the key as name

print(f"the winner is: {winner}. With {highest_price}")

替代解決方案

這里有一個不使用for循環的替代方法。 它還使用轉換后的數據結構。

#!/usr/bin/python3
dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

better_dict = dict(zip(dictionary1["name"], dictionary1["price"]))
# result --> {'a': 55, 'b': 100, 'c': 25}

# Find key with highest price
winner = sorted(better_dict, key=lambda k: better_dict[k])[-1]
# Get highest price by winners name
highest_price = better_dict[winner]

print(f"the winner is: {winner}. With {highest_price}")

我將嘗試為您分解winner =行。 sorted(better_dict) (沒有key= .)將返回字典的鍵(名稱)。 但是你想要這些值。 所以key=lambda k: better_dict[k]告訴sorted()使用lambda function 返回由鍵k索引的元素的值。 因為sorted()默認使用升序(從最低價到最高價),所以我們使用返回列表的最后一個元素來獲取價格最高的名稱。 您可以通過[-1]訪問列表的最后一個元素。

排隊:

dictionary1["name"][dictionary1["price"].index(max(dictionary1["price"]))]
  1. 我會重新排列你的字典的結構,所以字母 a、b、c 是鍵,數字是值

    dictionary1 = { "a": 55, "b": 100, "c": 25 }
  2. 您可以按值對字典進行排序並反轉排序順序,以便具有最高鍵的條目位於第一個 position。這可以通過使用已sorted的 function 來完成。您必須在dictionary1.get上設置key參數以進行排序按值並將reverse參數設置為 true。 最后,您必須訪問第一個元素,並返回具有最高值的鍵。

    sorted(dictionary1, key=dictionary1.get, reverse=True)[0]

這是完整的代碼:

dictionary1 = {
    "a": 55,
    "b": 100,
    "c": 25
}
max_entry = sorted(dictionary1, key=dictionary1.get, reverse=True)[0]

print(f"the winner is: {max_entry}. With {dictionary1[max_entry]}")

你得到這個錯誤的原因是,因為你試圖將整個列表“價格”與變量 highest_price 進行比較

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM