繁体   English   中英

在 python 中,我试图使用 for 循环计算列表中的每个元素,但它多次返回元素出现次数

[英]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.

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