首页 > 解决方案 > 用于变量 += 用户输入的 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(" ") 但它仍然单独添加它

标签: python

解决方案


使用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

推荐阅读