字的最大频率值 [英] Maximum frequency value for word
问题描述
寻求家庭作业帮助
我得到一个列表,并要求其在列表中查找最常出现的值并返回次发生。这个问题相当大,我自己一个人就可以解决其他问题,但这让我很沮丧。我还要补充一点,这是一项对任何指导都值得赞赏的任务。
I am given a list and asked to find the most occurring value in a list and returns the amount of times it is occurred. This question is fairly big and i have managed to get through the other parts by myself but this one stumped me.I should add that this is for an assignment any guidance would be appreciated.
问题陈述:最大(单词)频率
例如,在带有以下单词 [' big, big, bat, bob, book]
最大频率为2,即big是最频繁出现的单词,因此2为最大频率。 / p>
For example in a book with the following words ['big', 'big', 'bat', 'bob', 'book']
the maximum frequency is 2, i.e., big is the most frequently occurring word, therefore 2 is the maximum frequency.
def maximum_frequency(new_list):
word_counter = {}
for word in new_list:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
我已经走了这么远,但我不确定它是否正确/在哪里从这里开始
I have gotten this far but I am not sure if its right/where to go from here
推荐答案
如何操作:
def maximum_frequency(new_list):
word_counter = {}
for word in new_list:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
max_freq = max(word_counter.items(), key=(lambda x: x[1]))
return max_freq
if __name__ == '__main__':
test_data = ['big', 'big', 'bat', 'bob', 'book']
print(maximum_frequency(test_data))
输出:
('big', 2)
在Python 2和3上运行良好并返回结果,将其作为最常见单词和出现次数的元组。
Works fine with Python 2 and 3 and returns result as a tuple of most frequent word and occurrences count.
编辑:
如果您不这样做,完全不关心哪个单词具有最高的计数,而您只想要可以将其简化的频率数字即可:
If you don't care at all which word has the highest count and you want only the frequency number you can simplify it a bit to:
def maximum_frequency(new_list):
word_counter = {}
for word in new_list:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
return max(word_counter.values())
if __name__ == '__main__':
test_data = ['big', 'big', 'bat', 'bob', 'book']
print(maximum_frequency(test_data))
这篇关于字的最大频率值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!