2017-09-26 60 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] 
相关问题