python - 在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
我该如何避免这种情况?
解决方案
您可以使用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()
推荐阅读
- swift - Swift 5:什么是“转义闭包捕获变异的“自我”参数”以及如何修复它
- python - 为抽象模型在自身上创建关系
- python - 累积列,而其他列在熊猫中没有变化
- jquery - 一个附加的元素在滚动后一直附加(无限),它应该只附加一次
- testing - 步骤定义检测仅在项目配置为黄瓜项目时有效。- 虚拟机
- powershell - Octopus Deploy:Slack Notifier 步骤失败并显示“无法创建 SSL/TLS 安全通道”
- c++ - Magick++ 总是生成黑色图像
- java - fluentwait 类型中的方法 withtimeout(duration)
不适用于参数 (int, timeunit) - reactjs - Next.js 和 redux-persist;如何在我的 Web 应用程序中保留经过身份验证的用户?
- json - Sharepoint Online 列格式 - 将值显示为文本