[英]In python, I'm trying to count each element in a list using a for loop, but it returns the element occurrence n many times
此函數多次返回元素出現次數:
def cold_compress():
l = int(input())
inp_list = []
num_list = []
for lines in range(l):
b = input()
inp_list.append(b)
print(b)
for item in inp_list:
for x in item:
print(item.count(x))
例如:如果我的輸入是:
嗚嗚嗚
33jjji
...它將輸出:
3
3
3
4
4
4
4
2
2
3
3
3
1
我如何避免這種情況?
您可以使用Counter()來計算列表中的元素
示例代碼:
from collections import Counter
listr = ["one","two","three","three","three","three",]
print(dict(Counter(listr)))
輸出
{'one': 1, 'two': 1, 'three': 4}
在您的代碼中實現 Counter():
from collections import Counter
def cold_compress():
listr = list(input())
print(dict(Counter(listr)))
cold_compress()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.