作者:肥妹---君 | 来源:互联网 | 2022-12-10 13:56
我有一个包含许多字符串的列表.有些字符串是重复的,所以我想计算它们重复的次数.对于单数字符串,我只会打印它,因为重复的字符串我想打印它具有的重复数.代码如下:
for string in list:
if list.count(string) > 1:
print(string+" appeared: ")
print(list.count(string))
elif list.count(string) == 1:
print(string)
但是它有一些问题,因为它打印重复字符串的所有实例.例如,如果列表中有两个"hello"字符串,它将打印hello appeared 2
两次.那么有没有办法跳过检查重复字符串的所有实例?感谢帮助.
1> jpp..:
list.count
在循环中是昂贵的.它将解析每个单词的整个列表.这是O(n 2)的复杂性.你可以遍历一组单词,但那是O(m*n)复杂度,仍然不是很好.
相反,您可以使用collections.Counter
一次解析列表.然后迭代你的字典键值对.这将具有O(m + n)复杂度.
lst = ['hello', 'test', 'this', 'is', 'a', 'test', 'hope', 'this', 'works']
from collections import Counter
c = Counter(lst)
for word, count in c.items():
if count == 1:
print(word)
else:
print(f'{word} appeared: {count}')
hello
test appeared: 2
this appeared: 2
is
a
hope
works