python - 如何统计列表中重复项的出现次数和次数?

标签 python

我正在尝试计算列表中字符串的重复字符;另外,我根据变量是否重复 2 次或 3 次来递增变量。

但是,在我的 250 个字符串测试列表中,它返回的总计数为 641,所以我确定出了问题。

这是我的代码:

def findDupesNum(listy):
    a = []      # the current string's character list
    b = 0       # the 2-dupe counter
    c = 0       # the 3-dupe counter
    for i in listy:
        a.clear()
        for x in i:
            if x in a and a.count(x) == 1 and x != '':
                b += 1
            elif x in a and a.count(x) == 2 and x != '':
                c += 1
                b -= 1
            a.append(x)
        print('b = ' + str(b) + ' and c = ' + str(c))

最佳答案

使用字典来计算出现次数会更容易一些:

def findDupesNum(listy):
    for i in listy:
        counts = {}
        for x in i:
        if x:
            counts[x] = counts.get(x, 0) + 1
        doubles = 0
        triples = 0
        for i in counts:
            if counts[i] == 2:
                doubles = doubles + 1
            elif counts[i] == 3:
                triples = triples + 1

        print('{} doubles and {} triples'.format(doubles, triples))

关于python - 如何统计列表中重复项的出现次数和次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733449/

相关文章:

python - 比较多列中的值并在 Python 中的另一列中添加新值

python - 加载预训练模型会抛出 ValueError : bad marshal data (unknown type code)

python - 使用 R、Python 或 EXCEL 查找风速最高和最低的一天

python - 解析字符串模式 - Python

python - 尝试安装 Odoo 应用程序时出错

python - 如何在Google Colab笔记本中模拟Python按键?

python - Peewee 原子更新复杂逻辑

python - 通过客户端/服务器的Python子进程更改目录

python - 带反馈的多标签文本分类

python - Flask:在网站而不是控制台上显示打印?