如何计算数组中的值并将它们转换为字典

时间:2017-09-26 04:40:49

标签: python arrays list dictionary

我有一个程序在数组中返回一组年龄,我想计算它们并将它们放在字典中,我尝试了以下但没有结果。请帮忙!

让我们说我有一个数组如下:

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}

所以返回计数实际上等于每个年龄值的计数

当我尝试输入一个变量时,它只附加第一个数字,或说它不可迭代! 如何将其存储到列表中,更好的方法是如何创建包含集合(年龄)的字典和每个集合(年龄)的计数

谢谢

3 个答案:

答案 0 :(得分:2)

试试这个!

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

答案 1 :(得分:1)

有很多不同的方法可以实现这一目标。第一个也是最简单的方法是从Counter导入collections类。

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

答案 2 :(得分:0)

如果您需要存储计数,最好使用Python dicts。

Highcharts.chart('container', {
    xAxis: {
        tickInterval: 24 * 3600 * 1000, // one day
        type: 'datetime'
    },

    yAxis: {
        plotLines: [{
            color: 'red',
            width: 2,
            value: 100,
            label: {
                text: 'Plot line',
                align: 'right'
            }
        }]
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
        pointStart: Date.UTC(2010, 0, 1),
        pointInterval: 24 * 3600 * 1000
    }]
});