首页 > 解决方案 > 在python中,我试图使用for循环计算列表中的每个元素,但它多次返回元素出现n

问题描述

此函数多次返回元素出现 n 次:

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

我该如何避免这种情况?

标签: pythonpython-3.xpyscripter

解决方案


您可以使用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()

推荐阅读