【发布时间】:2022-06-15 23:11:04
【问题描述】:
我被要求组织一个文本文件,其中包含格式为 food: category 的食物列表,以便我的代码输出一个字典,其中包含每个食物类别中最常见的食物(我们没有事先给出类别)。字典的格式应为类别:食物。
我已经设法降低了频率部分。但是在两种食物频率相同且类别相同的情况下,我们应该使用字母表中排在第一位的食物。这就是我的代码出错的地方。
from collections import Counter
def get_most_popular_foods(file_path):
""" Read in survey and determine the most common food of each type.
Parameters
----------
file_path : str
Path to text file containing favorite food survey responses.
Returns
-------
Dict[str, str]
Dictionary with the key being food type and value being food.
"""
file = open(file_path, 'r')
data = file.read()
ans = data.split("\n")
nA = []
t = []
for i in ans:
if(i.find(", ")!=-1):
t = i.split(", ")
nA.append(t[0])
nA.append(t[1])
else:
nA.append(i)
t2 = []
nA2 = []
for n in nA:
t2 = n.split(": ")
nA2.append(t2)
cnt = Counter()
for word in nA:
cnt[word] += 1
dict = {}
t2 = []
a = ""
b = ""
s = ''
for w in cnt:
t2 = w.split(": ")
if t2[1] in dict:
s = dict[t2[1]]+": "+t2[1]
if(cnt[w]>cnt[s]):
dict[t2[1]] = t2[0]
elif(cnt[w] == cnt[s]):
if(t2[0]>dict[t2[1]]): # changing > to < makes another error but in reverse
dict[t2[1]] = t2[0]
else:
dict[t2[1]] = t2[0]
print(data)
print()
print(cnt)
print()
print(dict)
return dict
这个输出:(最后一行是返回值。其余的用于上下文/测试)
apples: fruit
candy: dessert
cookies: dessert, tuna: meat
carrots: vegetable, spinach: vegetable
bananas: fruit
pork: meat
chicken: meat
pork: meat, carrots: vegetable
chicken: meat
kale: vegetable
pork: meat
bananas: fruit
kale: vegetable
chicken: meat, broccoli: vegetable
cookies: dessert, peaches: fruit
apples: fruit
candy: dessert, kale: vegetable
peaches: fruit
Counter({'pork: meat': 3, 'chicken: meat': 3, 'kale: vegetable': 3, 'apples: fruit': 2, 'candy: dessert': 2, 'cookies: dessert': 2, 'carrots: vegetable': 2, 'bananas: fruit': 2, 'peaches: fruit': 2, 'tuna: meat': 1, 'spinach: vegetable': 1, 'broccoli: vegetable': 1})
{'fruit': 'peaches', 'dessert': 'cookies', 'meat': 'pork', 'vegetable': 'kale'}
什么时候输出应该是:
{'fruit': 'apples', 'dessert': 'candy', 'meat': 'chicken', 'vegetable': 'kale'}
看来我评论的那一行是问题所在。如果两种食物出现的次数相同并且属于同一类别,那么即使下一种食物按字母顺序排列,它似乎总是会更新字典中的键。例如,'fruit': 'peaches' 应该是 'fruit': 'apples' 时返回的内容。
我试过翻转比较符号,但这只会让我的代码更加不准确。这样做,只是忽略了食物的频率。
【问题讨论】:
-
这段代码的编写方式非常难以理解。你的变量名都是1-3个字母,没有有用的cmets,查看代码本身的功能也看不出来。一切都在一个功能中完成,我看不到任何细分或组织。我打算看看问题出在哪里,但我想我和这里的大多数其他人真的不想花 20 多分钟试图从这段代码中找出意义。我强烈建议编写其他人可以理解的代码——这就是高级代码的全部意义所在。
-
这里提问的时候最好提供minimal reproducible example来说明问题,不多说了。
标签: python string dictionary comparison