繁体   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