2017-09-26 28 views
0

我有一個程序返回一組數組內的年齡,我想要計算它們並將它們放入字典中,我嘗試了以下但沒有結果。請幫忙!如何計算數組內的值並將它們轉換爲字典

比方說,我有一個數組如下:

ages = [20,20,11,12,10,11,15] 
# count ages inside of array, I tried this 
for i in set(ages): 
    if i in ages: 
     print (ages.count(i)) 
# result returns the following 
    1 
    2 
    1 
    1 
    2 

這是非常合情合理的,就好像我們看一組(年齡),它等於= {10,11,12,15,20}

所以返回的次數實際上等於每個值的年齡

當我試圖把一個變量雖然計數,僅追加第一個數字,或者說,它是不是可迭代! 我怎樣才能將其存儲到一個列表,甚至更好,我怎樣才能使包含集(年齡)和計數每個組的字典(年齡)

謝謝

+0

可以使用計數器它https://docs.python.org/3/library/collections.html#collections.Counter – AndMar

+0

謝謝你,但我手動試圖做到這一點,而不庫 – MAUCA

回答

1

有很多不同的方法來實現這一點。第一種,也可能是最簡單的,是從collections導入Counter類。

from collections import Counter 
ages = [20,20,11,12,10,11,15] 
counts = Counter(ages) 
# Counter({10: 1, 11: 2, 12: 1, 15: 1, 20: 2}) 
# if you want to strictly be a dictionary you can do the following 
counts = dict(Counter(ages)) 

的另一種方法是做一個循環:

counts = {} 
for a in ages: 
    # if the age is already in the dicitonary, increment it, 
    # otherwise, set it to 1 (first time we are seeing it) 
    counts[a] = counts[a] + 1 if a in counts else 1 

最後,dict comprehension。除了它是一條線以外,它在循環中沒有任何優勢。你還是最終列表中的遍歷每個變量:

counts = {a:ages.count(a) for a in ages} 

既然你問更多有關ternary operator,這個循環就等於說:

counts = {} 
for a in ages: 
    # if the age is already in the dicitonary, increment it, 
    # otherwise, set it to 1 (first time we are seeing the number) 
    if a in counts: 
    counts[a] = counts[a] + 1 
    print("Already seen", a, " -- ", counts[a]) 
    else: 
    counts[a] = 1 
    print("First time seeing", a, " -- ", counts[a]) 

三元運算符可以讓我們在一行中完成此模式。語言很多有它:

  1. C/C++/C#
  2. JavaScript
+0

太棒了!我有一個問題,如何在設置變量時使用if和else語句? – MAUCA

+0

它被稱爲[三運算符。](http://pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/)它真的只是釋放了一些代碼行。這相當於'如果計數:計數[a] =計數[a] + 1 else:計數[a] = 1'。 – TheF1rstPancake

+1

是不是'從集合中導入Counter'無效的語法? – mentalita

2

試試這個!

ages = [20,20,11,12,10,11,15] 
dic = {x:ages.count(x) for x in ages} 
print dic 
0

如果你需要存儲計數,更好您使用Python類型的字典。

ages = [20,20,11,12,10,11,15] 
age_counts={} #define dict 
for i in ages: 
    #if age_counts does not have i, set its count to 1 
    #increment otherwise 
    if not age_counts.has_key(i): 
     age_counts[i]=1 
    else: 
     age_counts[i]+=1 
#you can now have counts stored 
for i in age_counts: 
    print i, age_counts[i] 
相關問題