Python字典合并两个字典并构建累积

时间:2016-01-26 21:39:31

标签: python dictionary

我有两个数组date_INdate_OUT,其中包含动物进入和离开农场的日期。现在我想绘制总人口随时间变化的情况。

date_IN, date_OUT
26.09.1999,19.12.2006
26.09.1999,19.01.2005
26.09.1999,15.02.2007
26.09.1999,29.03.2006
...

我尝试先计算每天的条目,从进入的动物数量中减去离开农场的动物数量,然后总结排序值。 但不幸的是减法无效。

date_EIN, date_AUS=np.genfromtxt("Gesamtbestand.txt",delimiter=',',unpack = True, converters={ 0: mdates.strpdate2num('%d.%m.%Y'), 1: mdates.strpdate2num('%d.%m.%Y') or 0})

c = Counter(date_EIN)
d = Counter(date_AUS)
tn_each_day = c - d

sorted_keys = sorted(tn_each_day,key=tn_each_day.get)
z = cumsum(sorted(d.values())) # or z = cumsum([d[k] for k in sorted_keys])
tn = dict(zip(sorted_keys,z))

有没有人知道如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

为简洁起见,我们使用数字而不是日期:

>>> from collections import Counter
>>> import itertools as it
>>> import operator as op
>>> ein = Counter([1,2,2,3,3])
>>> aus = Counter([1,2,3,4])
>>> delta = {k:ein.get(k,0)-aus.get(k,0) for k in set(it.chain(ein,aus))}
>>> delta
{1: 0, 2: 1, 3: 1, 4: -1}
>>> sorted_dates = sorted(delta)
>>> population = dict(zip(sorted_dates, it.accumulate((delta[k] for k in sorted_dates), add)))
>>> population
{1: 0, 2: 1, 3: 2, 4: 1}

即。对于每个日期,population保留农场中存在的动物数量。

e.g。

约会1一只动物进入并且一只动物出去了 - > 0农场人口

约会2两只动物进入并且一只外出 - > 1个农场人口

约会3两只动物进入并且一只外出 - > 2农场人口

约会4零个动物进入并且一个熄灭 - > 1个农场人口

答案 1 :(得分:0)

从另一个Counter中减去Counter只会从第一个Counters中删除Counter中存在的密钥。这不是你想要做的。这是一个有效的例子:

from collections import Counter

def compareDates(d1, d2):
    d1, d2 = d1.split('.'), d2.split('.')
    for i in range(2,-1,-1):
        if d1[i] > d2[i]:
            return 1
        if d1[i] < d2[i]:
            return -1
    return 0


IN  = ['26.09.1999', '26.09.1999', '26.09.1999', '26.09.1999', '26.8.2008']
OUT = ['19.12.2006', '19.01.2005', '15.02.2007', '29.03.2006', '27.8.2008']

c_IN  = Counter(IN)
c_OUT = Counter(OUT)

tn_each_day  = {}

for date, count in c_IN.items():
    if date not in tn_each_day :
        tn_each_day[date] = 0
    tn_each_day[date] += count

for date, count in c_OUT.items():
    if date not in tn_each_day :
        tn_each_day [date] = 0
    tn_each_day[date] -= count

cumulative = {}
population = 0
for date in sorted(tn_each_day, cmp=compareDates):
    population += tn_each_day[date]
    cumulative[date] = population
    print '{}: {}'.format(date, population)

这会产生一个输出:

26.09.1999: 4
19.01.2005: 3
29.03.2006: 2
19.12.2006: 1
15.02.2007: 0
26.8.2008: 1
27.8.2008: 0