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))
解决方案
使用 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))
推荐阅读
- rxjs - RxJS Observables 和轮子事件
- c# - 如何使用 MigraDoc 在 PDF 中添加流(无文件)图像?
- x86 - 在运行时从 simd 寄存器中获取任意浮点数?
- c# - ASP.NET CORE 2.1 - FromQuery 不起作用?
- python - 由于参数不正确,Python gunicorn worker 退出?
- python - 有谁知道为什么我得到一个完全黑色的 geotiff,因为这个 shapefile 是从光栅中的另一个 geotiff 中剪下来的?
- java - 在 Cucumber 步骤中自动装配字段会产生 NullPointerException
- vb.net - VB.NET - 将文本附加到文本文件的最后一行会留下(有时)一个空行
- java - Eclipse SpringTestSuite 4/Spring Boot 2 Maven 如何在运行测试时排除类执行?
- jenkins - 在 Jenkins Pipeline 的 shell 脚本部分定义变量