简体   繁体   English

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

[英]Is there a way to calculate the number of occurrences of a string in a list without using a dictionary?

Is there another way to calculate the number of occurrences without using a dictionary like this code?有没有另一种方法来计算出现次数而不使用像这样的代码的字典? I mean, I want the same result as this code but without the dict.我的意思是,我想要与此代码相同的结果,但没有 dict。

This code displays:此代码显示:

apple 3
bread 2
orange 1

Code:代码:

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))

If the charset is known and limited (lower case ASCII alphabet for example), you could allocate an array, and increment the count corresponding to the index of a character every time you see it.如果字符集是已知且有限的(例如小写 ASCII 字母表),您可以分配一个数组,并在每次看到它时增加与字符索引相对应的计数。 This, however, is waste of space since you may never encounter some characters at all.但是,这会浪费空间,因为您可能根本不会遇到某些字符。

Option 1 : Use counters选项 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

Output:输出:

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

Option 2: Use count and set选项 2:使用计数和设置

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

Output:输出:

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

If you want to just print it without saving in a dictionary, use this:如果您只想打印而不保存在字典中,请使用以下命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM