首页 > 解决方案 > 如何计算列表中重复的出现和数量?

问题描述

我正在尝试计算列表中字符串的重复字符;另外,我根据它是重复的 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))

标签: python

解决方案


使用 dict 计算出现次数会更容易一些:

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))

推荐阅读