[英]Python list of frequent occurrences in a list of strings
I'm writing a python function that consumes a list of strings and produces a list of the most frequently occurring items. 我正在编写一个python函数,该函数使用字符串列表并生成最频繁出现的项目的列表。
For example: 例如:
>>> trending(["banana", "trouble", "StarWars", "StarWars", "banana", "chicken", "BANANA"])
["banana", "StarWars"]
but 但
>>> trending(["banana", "trouble", "StarWars", "Starwars", "banana", "chicken"])
["banana"]
So far, I've written a function that produces only the first word that appears frequently instead of a list of words that appear frequently. 到目前为止,我已经编写了一个仅产生经常出现的第一个单词而不是经常出现的单词列表的函数。 Also, my list contains the index of that one frequent item. 此外,我的列表还包含该一项经常性项目的索引。
def trending(slst):
words = {}
for word in slst:
if word not in words:
words[word] = 0
words[word] += 1
return words
How can I fix this function to produce a list of the most frequently occurring items (instead of the first of the most frequently occurring items) and how do I remove the index? 如何修复此函数以产生最频繁出现的项目的列表(而不是最频繁出现的项目的第一个),以及如何删除索引?
Without the use of Counter
you can make your own counter with a dict
and extract frequent items: 如果不使用Counter
,则可以使用dict
来创建自己的计数器并提取频繁项:
def trending(slst):
count = {}
items = []
for item in set(slst):
count[item] = slst.count(item)
for k, v in count.items():
if v == max(count.values()):
items.append(k)
return items
In [1]: from collections import Counter
In [2]: l = ["banana", "trouble", "StarWars", "StarWars", "banana", "chicken", "BANANA"]
In [3]: Counter(l)
Out[3]: Counter({'StarWars': 2, 'banana': 2, 'BANANA': 1, 'trouble': 1, 'chicken': 1})
With Counter(l).most_common(n)
you can get the n
most common items. 使用Counter(l).most_common(n)
您可以获得n
最常见的项目。
Your trending()
function is basically what the Counter
does as well. 您的trending()
函数基本上也是Counter
所做的。 After counting the word occurrences, you can get the maximum number of occurrences using max(words.values())
. 在计算单词出现次数之后,您可以使用max(words.values())
获得最大出现次数。 This can be used for filtering your word list: 这可以用于过滤单词列表:
def trending(slst):
...
max_occ = max(words.values())
return [word for word, occ in words.items() if occ == max_occ]
The following solution uses only lists. 以下解决方案仅使用列表。 No dictionary
, set
or other Python collection is used: 不使用dictionary
, set
或其他Python集合:
def trending(words):
lcounts = [(words.count(word), word) for word in words]
lcounts.sort(reverse=True)
ltrending = []
for count, word in lcounts:
if count == lcounts[0][0]:
if word not in ltrending:
ltrending.append(word)
else:
break
return ltrending
ltests = [
["banana", "trouble", "StarWars", "StarWars", "banana", "chicken", "BANANA"],
["banana", "trouble", "StarWars", "Starwars", "banana", "chicken"]]
for test in ltests:
print trending(test)
It gives the following output: 它给出以下输出:
['banana', 'StarWars']
['banana']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.