我正在尝试使用Python在列表中找到字符串的最大出现次数,我的代码目前是:
def count_occurences(input_string):
list1 = []
items = input_string.split(", ")
for item in items:
item = item.rstrip()
max=0
for i in items:
count = input_string.count(i)
if count > max:
max = count
for j in items:
frequency = input_string.count(j)
if frequency == max:
list1.append(j)
list1.append(max)
return list1
不需要编写自己的算法,您可以简单地使用collections
包中的内置Counter
。这个类基本上是一个字典,项作为键,频率作为值:
from collections import Counter
string = 'mary, bob, mary, bob, alex, julie'
names = [name.strip() for name in string.split(', ')]
frequencies = Counter(names)
max_frequency = max(frequencies.values())
max_frequency_names = [name
for name, frequency in frequencies.items()
if frequency == max_frequency]
print(max_frequency_names)
只是一个困惑是,你的string
变量是一个字符串,而不是一个列表,这是你问的。这是我想出来的:
def count(a):
dictionary={}
for x in a:
try:
dictionary[x]+=1
except Exception:
dictionary[x]=1
return (dictionary)
string = 'mary, bob, mary, bob, alex, julie'
s=string.split(",")
print(count(s))
您可以通过将每个名称分配给一个变量来访问每个名称的计数,并像这样调用它:
a=count(s)
s["bob"] #returns 2