簡體   English   中英

計算由空格分隔的未指定數量的整數,並使用字典查找python中每個數字的出現

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

樣本輸出

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

所以我是python的新手,但是我想開始這樣做:

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

除了我嘗試的每個循環不斷說不能將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()

對於給定的輸出,我想要一個類似的解決方案(但使用字典)

嘗試

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

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

或類似以下注釋中的示例:

import collections

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

我只能猜測您正在嘗試這樣的事情

>>> 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'

像這樣:

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

應該工作正常。 請注意,對於此問題,您可能不需要轉換為int 留下數字str應該也一樣

不導入任何東西

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

輸出

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM