【发布时间】:2020-07-22 19:22:05
【问题描述】:
我编写了一个函数,它接受一个列表作为输入并返回列表中最常见的项目。
##Write the function
def most_frequent(List):
dict = {}
count, itm = 0, ''
for item in reversed(List):
dict[item] = dict.get(item, 0) + 1
if dict[item] >= count :
count, itm = dict[item], item
return(item)
return num
# verfiy the code
list = [5,42,34,6,7,4,2,5]
print(most_frequent(list))
然后下载两个文本文件以获取最常用的单词。
# Download the files restaurants.txt and restaurant-names.txt from Github
!curl https://raw.githubusercontent.com/ipeirotis/introduction-to-python/master/data/restaurant-names.txt -o restaurant-names.txt
!curl https://raw.githubusercontent.com/ipeirotis/introduction-to-python/master/data/restaurants.txt -o restaurants.txt
# create the list from the restaurants.txt
List = open("restaurants.txt").readlines()
# get the most most frequent restaurant names
print("The most frequent restaurant names is ",most_frequent(List))
print(most_common(List))
但是当我尝试查找出现在餐厅名称中的最常用词时。我得到了同样的结果。你能帮忙检查一下这是否正确吗?谢谢
# create the list from the restaurants.txt
List = open("restaurants.txt").readlines()
# get the most most frequent restaurant names
print("The most frequent restaurant names is ",most_frequent(List))
【问题讨论】:
-
有一个内置的类可以为你做到这一点...
collections.Counter(List).most_common(1)[0][0] -
当您使用已知值测试您的函数时,它是否有效?