有没有另一种方法来计算出现的次数而不使用类似于此代码的字典?
我的意思是,我想要和这个代码一样的结果,但是没有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:
如果字符集是已知且有限的(例如,小写ASCII字母),则可以分配一个数组,并在每次看到它时增加与字符索引对应的计数。但是,这是浪费空间,因为您可能永远不会遇到某些角色
选项1:使用计数器
输出:
选项2:使用计数和设置
输出:
如果只想打印而不保存在词典中,请使用以下方法:
相关问题 更多 >
编程相关推荐