有没有一种方法可以在不使用字典的情况下计算字符串在列表中的出现次数?

2024-10-05 14:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有另一种方法来计算出现的次数而不使用类似于此代码的字典? 我的意思是,我想要和这个代码一样的结果,但是没有dict

此代码显示:

apple 3
bread 2
orange 1

代码:

txt = ["apple", "bread", "apple", "orange", "apple", "bread"]
dic ={}
for c in texte:
  lettres[c] = lettres.get(c, 0) + 1

for i in sorted(lettres):
 print(i,lettres.get(i))

Tags: 方法代码intxtappleforget字典
2条回答

如果字符集是已知且有限的(例如,小写ASCII字母),则可以分配一个数组,并在每次看到它时增加与字符索引对应的计数。但是,这是浪费空间,因为您可能永远不会遇到某些角色

选项1:使用计数器

from collections import Counter

txt = ["apple", "bread", "apple", "orange", "apple", "bread"]

keys = Counter(txt).keys() # equals to list(set(txt))
occ = Counter(txt).values() # counts the number of occurrences

输出:

['apple', 'bread', 'orange']
[3, 2, 1]

选项2:使用计数和设置

occ = {i: txt.count(i) for i in set(txt)}

输出:

{"apple": 3, "bread": 2, "orange": 1}

如果只想打印而不保存在词典中,请使用以下方法:

for i in set(txt):
   print(i, txt.count(i))

相关问题 更多 >