简体   繁体   English

计算由空格分隔的未指定数量的整数,并使用字典查找python中每个数字的出现

[英]counting an unspecified number of integers separated by spaces and finding occurrences of each number in python using dictionary

Sample Output 样本输出

Enter numbers separated by spaces :1 2 3 3 2 2 2 1 3 4 5 3

{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}

1 occurs 2 times

3 occurs 4 times

2 occurs 4 times

5 occurs one time

4 occurs one time

So I'm a total newbie at python but I was thinking of starting off like this : 所以我是python的新手,但是我想开始这样做:

d = {}     
user = input("Enter numbers separated by spaces :") 
data = user.split() 

Except every loop i tried kept saying that I cant convert str() to int(), I'd appreciate any help, I've been staring at this problem for a few hours..this is something I tried for when input is string, trying to implement something similar for dictionary 除了我尝试的每个循环不断说不能将str()转换为int()之外,我都会感谢您的帮助,我一直在盯着这个问题几个小时..这是我在输入为字符串时尝试的东西,尝试为字典实现类似的功能

def countdigits (aString):  
  c = 10 * [0]

  for e in aString: 
    c[int(e)] += 1 

  return c 

def main (): 
  n = 0 

  for v in (countdigits(str(input('Enter a string: ')))): 
    if v == 1: 
      print(n, "occurs 1 time")
    elif v!=0:
      print(n, "occurs", v, "times")

    n += 1 

main()

I'd like a similar solution to this, for the ouput given (but using dictionaries) 对于给定的输出,我想要一个类似的解决方案(但使用字典)

Try 尝试

d = {i:data.count(i) for i in data}

for k,v in d:
    print "{0} occurs {1} times\n".format(k,v)

or like examples from the comments below: 或类似以下注释中的示例:

import collections

for a,b in collections.Counter(data).items():
    print "{0} occurs {1} times\n".format(a,b)

I can only guess that you were attempting something like this 我只能猜测您正在尝试这样的事情

>>> user = "1 2 3 3 2 2 2 1 3 4 5 3"
    >>> data = int(user)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: invalid literal for int() with base 10: '1 2 3 3 2 2 2 1 3 4 5 3'

Something like this: 像这样:

data = user.split()
for item in data:
   number = int(item)

should work fine. 应该工作正常。 Note that you probably don't need to convert to int for this problem. 请注意,对于此问题,您可能不需要转换为int Leaving the numbers a str should work just as well 留下数字str应该也一样

without importing anything 不导入任何东西

nk="1 2 3 3 2 2 2 1 3 4 5 3"
nk=nk.split()
result={}
for x in nk:
    result.setdefault(x,0)
    result[x]+=1
print result

output 输出

{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM