0

我有一本带有 {ID: (INITIALS, DATE, AREA)} 的字典,如下所示:

>> mydict = {1: ('JN', '2012-06-13', 2),
             2: ('JN', '2012-06-13', 5),
             3: ('JN', '2012-06-14', 8),
             4: ('AM', '2012-06-13', 3),
             5: ('OV', '2012-06-14', 4)}

我已经能够总结出这样的价值观:

>> from collections import Counter
>> mycounter = Counter((val[0], val[1]) for val in mydict.values())
>> for (initials, date), count in mycounter.iteritems():
       print ', '.join(initials, date, str(count))

JN, 2012-06-13, 2
JN, 2012-06-14, 1
AM, 2012-06-13, 1
OV, 2012-06-14, 1

我还想包括 mydict 中值的 AREA 总和,从而导致:

JN, 2012-06-13, 2, 7
JN, 2012-06-14, 1, 8
AM, 2012-06-13, 1, 3
OV, 2012-06-14, 1, 4

谢谢!


编辑:工作代码(根据 Ashwini 的代码稍作修改):我将 v[1] 移动到一个元组中加入 v[0],因此它将根据首字母和日期进行总结(我在最初的问题中没有说清楚,现在进行编辑以反映这一点),然后计算计数并对面积求和。Martijn 的代码也有效,但这个解决方案需要少一个导入。

stats = {}
for k, v in mydict.items():
    d = stats.setdefault((v[0], v[1]), [0, 0])
    d[1] += v[-1]
    d[0] += 1
4

2 回答 2

1

您在Counter这里没有使用完整的 API,不妨将其替换为defaultdict

from collections import defaultdict

stats = defaultdict(lambda: [0, 0])

for entry in mydict.values():
    counts = stats[tuple(entry[:2])]
    counts[0] += 1
    counts[1] += entry[-1]

然后打印:

for (initials, date), (count, area) in stats.iteritems():
    print ', '.join((initials, date, str(count), str(area)))

输出:

OV, 2012-06-14, 1, 4
AM, 2012-06-13, 1, 3
JN, 2012-06-13, 2, 7
于 2013-06-15T12:27:57.063 回答
1

你可以在这里使用普通的字典:

>>> dic = {}
for k, v in mydict.items():
    d = dic.setdefault(v[0], [v[1], 0, 0])
    d[2] += v[-1]
    d[1] += 1
...     
>>> dic
{'OV': ['2012-06-14', 1, 4],
 'JN': ['2012-06-13', 2, 7],
 'AM': ['2012-06-13', 1, 3]}

遍历 dict 以获得预期的输出:

>>> for k,v in dic.items():
    print k +',',", ".join([str(x) for x in v])
...     
OV, 2012-06-14, 1, 4
JN, 2012-06-13, 2, 7
AM, 2012-06-13, 1, 3

如果订单很重要,那么您可以使用collections.OrderedDict

>>> from collections import OrderedDict
>>> dic = OrderedDict()
>>> for k, v in mydict.items():
         d = dic.setdefault(v[0], [v[1], 0, 0])
         d[2] += v[-1]
         d[1] += 1

>>> for k,v in dic.items():
...         print k +',',", ".join([str(x) for x in v])
...     
JN, 2012-06-13, 2, 7
AM, 2012-06-13, 1, 3
OV, 2012-06-14, 1, 4
于 2013-06-15T12:28:22.107 回答