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