变量+=用户输入的for循环

2024-05-14 22:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想尝试用空格分隔一些用户输入行,这些输入只能处理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(“”),但它仍然单独添加了它


Tags: 函数用户inforinputifcount数字
3条回答

您可以尝试将append添加到noOccur列表中,如下所示:

userIn = input('Please enter your numbers:  ') # 689 688 3405
separated = userIn.split(' ')
noOccur = []

for i in separated:
    loopCount = noOccur.count(i)
    if loopCount == 0:
        noOccur.append(i)

print(noOccur)

length = len(noOccur)
items = 0

while items < length:
    tempVar = noOccur[items]
    print(str(tempVar) + ": " + str(separated.count(tempVar)))
    items += 1

结果:

Please enter your numbers:  689 688 3405
['689', '688', '3405']
688: 1
689: 1
3405: 1

使用^{}计算可哈希元素(如字符串或数字)在iterable中出现的次数。可以像dict一样使用Counter对象进行进一步处理

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

我检查了你函数的更新,如果你没有任何限制,最好使用一个词汇:

userIn = input('Numbers:   ')


separated=userIn.split()
print(separated)

noOccur = {}

for item in separated:
  if item in noOccur.keys():
      noOccur[item]+=1
  else:
      noOccur[item]=1

for k,v in noOccur.items():
    print(str(k) + ": " + str(v))

结果:

Numbers:   1 2 3 100 1 2
['1', '2', '3', '100', '1', '2']
1: 2
2: 2
3: 1
100: 1

相关问题 更多 >

    热门问题