简体   繁体   English

Python中的字典循环有一些错误

[英]Having some errors with Loops of dictionaries in Python

I want to make a wine menu program giving the 1) name and 2) price of wine if the customers are putting the wine name with Python 3. To do this, I made a wine list consisting of dictionaries as below. 我想制作一个酒菜单程序,提供1)名称和2)酒的价格(如果客户使用Python 3输入酒的名称)。为此,我制作了一个包含字典的酒单,如下所示。

wine = [
{'Origin': 'A', 'Name': 'w1', 'price': 10000},
{'Origin': 'B', 'Name': 'w2', 'price': 2000},
{'Origin': 'C', 'Name': 'w3', 'price': 4000},
{'Origin': 'D', 'Name': 'w3', 'price': 55000},
{'Origin': 'E', 'Name': 'w2', 'price': 63000},
{'Origin': 'F', 'Name': 'w6', 'price': 80000}
]

wish_wine = input('Insert the wine what you want to have : ')

The algorithm I'm trying to realize is as follows: 我正在尝试实现的算法如下:

1) Try to search for the all elements in the list whether there is a wine the customer wants: 1)尝试搜索列表中的所有元素,是否有客户想要的葡萄酒:

2) If there is in the list, return all the results with their name and price. 2)如果在列表中,请返回所有结果及其名称和价格。

3) If there is no wine in the list, print 'Sorry, there is no wine...' message 3)如果列表中没有葡萄酒,则打印“对不起,没有葡萄酒...”消息

for i in range(len(wine)):
    if wish_wine in wine[i]['Name']:
        print('wine', wine[i]['Name'], 'is', wine[i]['price'], '$'.)
else:
    print('Sorry, there is no wine what you want.')

Here are the codes that I made for now, it works well in case of 3), but it also shows 'Sorry, there is no wine...' message even in the case of 2). 这是我现在编写的代码,在3)的情况下效果很好,但即使在2)的情况下,它也显示“对不起,没有酒...”的消息。

Thank you! 谢谢!

You're missing a break statement or a flag indicating you found the results. 您缺少一个break语句或一个标志,表明您已找到结果。

Also, instead of iterating over range(len(wine)) you may iterate straight over the wine list, which returns a single wine for each iteration. 同样,您可以直接在酒单上进行迭代,而不是遍历range(len(wine)) ,而酒单会在每次迭代中返回单个酒。 This will make your code more readable, maintainable and efficient: 这将使您的代码更具可读性,可维护性和效率:

wines_found = False
for w in wine:
    if wish_wine in w['Name']:
        print('wine', wine['Name'], 'is', wine['price'], '$'.)
        wines_found = True

if not wines_found:
    print('Sorry, there is no wine what you want.')

Keep in mind that if your wine name is "Merlot" and you check M in "Merlot" you will find that it passes. 请记住,如果您的酒名是“ Merlot”,并且M in "Merlot"勾选M in "Merlot"您会发现它通过了。 This will become an issue if you have multiple wines starting wtih M . 如果您有多种以M开头的葡萄酒,这将成为一个问题。

If you wish to avoid it, change if wish_wine in w['Name'] to if wish_wine == w['Name'] , and add a break . 如果希望避免这种情况, if wish_wine in w['Name']中的if wish_wine == w['Name']if wish_wine == w['Name'] ,并添加一个break

Perhaps you specifically intended to use this JSON-like data structure, but did you consider a hash table lookup schema? 也许您专门打算使用这种类似于JSON的数据结构,但是您是否考虑了哈希表查找架构?

>>> wine = [
...     {'Origin': 'A', 'Name': 'w1', 'price': 10000},
...     {'Origin': 'B', 'Name': 'w2', 'price': 2000},
...     {'Origin': 'C', 'Name': 'w3', 'price': 4000},
...     {'Origin': 'D', 'Name': 'w3', 'price': 55000},
...     {'Origin': 'E', 'Name': 'w2', 'price': 63000},
...     {'Origin': 'F', 'Name': 'w6', 'price': 80000}
... ]
>>> 
>>> wine_dict_lookup = {row['Name']: {'Origin': row['Origin'], 'price': row['price']} for row in wine}
>>> wine_dict_lookup
{'w1': {'Origin': 'A', 'price': 10000}, 'w2': {'Origin': 'E', 'price': 63000}, 'w3': {'Origin': 'D', 'price': 55000}, 'w6': {'Origin': 'F', 'price': 80000}}
>>> wish_wine = input('Insert the wine what you want to have : ')
>>> try:
...     print('wine', wish_wine, 'is', wine_dict_lookup[wish_wine]['price'], '$')
... except KeyError:
...     print('Sorry, there is no wine what you want.')
... 
wine w1 is 10000 $

This problem lends itself really well to a hash table, like a dictionary. 这个问题非常适合哈希表,例如字典。 Although, if you intend the line if wish_wine in wine[i]['Name']: to serve as a sort of fuzzy-lookup tool (ie to be able to match a string like "I want w1 ", then the different in performance between these two approaches is negligible. 虽然,如果您打算if wish_wine in wine[i]['Name']:if wish_wine in wine[i]['Name']:用作一种模糊查找工具(即,能够匹配“ I want w1 ”之类的字符串,则这两种方法之间的性能可以忽略不计。

The real benefit of using a dictionary is that lookups are O(1) , meaning constant-time with respect to how many different wines you have. 使用字典的真正好处是查找为O(1) ,这意味着相对于您拥有多少种不同的葡萄酒,它是恒定时间的。 Your list-lookup is O(n) , where n is the number of elements in your wine list, because you're iterating through potentially all wines to find the one that someone looked for. 您的列表查找为O(n) ,其中n是您的酒单中的元素数,因为您要遍历潜在的所有酒以找到某人想要的酒。

You can use collections.defaultdict to restructure your dictionary to order by wine name. 您可以使用collections.defaultdict来重组字典,以按酒名排序。 This only works if you are looking for an exact name match. 仅当您要查找完全匹配的名称时,此方法才有效。

from collections import defaultdict

wine_d = defaultdict(list)

for item in wine:
    wine_d[item['Name']].append(item)

Then accessing information for an input wine name is trivial: 然后访问输入葡萄酒名称的信息很简单:

wish_wine = input('Insert the wine what you want to have : ')

print(wine_d.get(wish_wine, 'No wine found'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM