python - 用于变量 += 用户输入的 for 循环
问题描述
所以我想尝试使用空格分隔一些用户输入行,该输入只能处理 int,我创建了一个变量,从拆分的用户输入中删除了相同的数字
for item in separated:
print(item)
loopCount = noOccur.count(item)
if loopCount == 0:
noOccur += item
例如,如果我输入一个超过 10 的数字,就会发生一些奇怪的事情
userIn = input('Numbers: ') # 0 8 89
但是该函数将最后一个数字分成['0', '8', '8', '9']
该功能以个位数工作,但不能以两位数工作
userIn = input('Please enter your numbers: ') # 689 688 3405
separated = userIn.split()
noOccur = []
for item in separated:
print(item)
loopCount = noOccur.count(item)
if loopCount == 0:
noOccur += item
length = len(noOccur)
i = 0
print(noOccur) # ["6", "8", "9", "6", "8", "8", "3", "4", "0", "5"]
print(separated)
while i < length:
tempVar = noOccur[i]
print(str(tempVar) + ": " + str(separated.count(tempVar)))
i += 1
我认为我的 for 循环有点坏,因为我尝试了答案中提到的 split(" ") 但它仍然单独添加它
解决方案
使用collections.Counter
, 计算可迭代元素(如字符串或数字)在可迭代对象中出现的次数。您可以Counter
像 a 一样使用对象dict
进行进一步处理。
from collections import Counter
userIn = input('Numbers: ') # 689 688 3405 688
separated = userIn.split() # ['689', '688', '3405', '688']
noOccur = Counter(separated) # Counter({'689': 1, '688': 2, '3405': 1})
for k,v in noOccur.items():
print(f'{k}: {v}')
# '689': 1
# '688': 2
# '3405': 1
推荐阅读
- shell - 根据输入打印星号
- c# - 如何使用工厂/策略模式返回不同的响应类型
- vue.js - 如何按条件在 ChartJs 中绘制自定义 x 轴值?
- reactjs - getInitialState() 在控制台中显示错误
- elasticsearch - elasticsearch中多个布尔查询的限制大小
- sql - sqlite 将每个进入和退出计算为一次进入
- angular - 可以在@Input: TemplateRef 中使用新的模板上下文语法吗?
- azure-application-insights - 应用洞察集合级别有什么区别
- python - Elasticsearch Python客户端:节点停止后如何恢复连接
- postgis - 在 osm2pgrouting 上无法打开目录