创造净现金流

时间:2013-10-10 17:51:51

标签: python

因此,如果在同一时间段内有两个现金流量,当我采用现金流并尝试创建净CF时,我遇到了一些问题。

基本上,我想从此开始:

time=[1,2,3,3]
cf=[100,500,1000,-500]

为:

time=[1,2,3]
cf=[100,500,500]

任何建议都会有所帮助,因为我对python很新。 谢谢。

3 个答案:

答案 0 :(得分:1)

使用collections.Counter

>>> from collections import Counter
>>> tm = [1,2,3,3]
>>> cf = [100,500,1000,-500]
>>> c = Counter()
>>> for t, ca in zip(tm, cf):
...     c[t] += ca
...     
>>> c
Counter({2: 500, 3: 500, 1: 100})

使用sorted并在c.iteritems上解压缩以获得预期的输出:

>>> cf, tm = zip(*sorted(c.iteritems()))
>>> cf
(1, 2, 3)
>>> tm
(100, 500, 500)

如果tm列表始终排序,那么您也可以使用itertools.groupby

>>> from itertools import groupby, izip
>>> tm_1 = []
>>> cf_1 = []
>>> for k, g in groupby(izip(tm, cf), key=lambda x:x[0]):
...     tm_1.append(k)
...     cf_1.append(sum(x[1] for x in g))
...     
>>> tm_1
[1, 2, 3]
>>> cf_1
[100, 500, 500]

time是一个内置模块,不要将它用作变量名。

答案 1 :(得分:1)

from collections import defaultdict

time=[1,2,3,3] 
cf=[100,500,1000,-500]

result = defaultdict(int)

for num,i in enumerate(time):
    result[i] += cf[num]   

time2 = list(result.keys())
cf2 = list(result.values())

答案 2 :(得分:0)

这不是我最大的作品,但它符合你的需要。

time=[1,2,3,3]
cf=[100,500,1000,-500]
transactions = zip(time, cf)
cf = list(set(sf))
cf.sort()

final_cf = []
for time in cf:
    total_period = 0
    for element in transactions:
        if element[0] == time:
            total_period += element[1]
    final_cf.append(total_period)

另一种方法是使用dict:

time=[1,2,3,3]
cf=[100,500,1000,-500]
transactions = zip(time, cf)
cf_unique = list(set(cf))
cf_unique.sort()
result = dict()

for moment in cf_unique:
result[moment] = 0
for transaction in transactions:
    if transaction[0] == moment:
        result[moment] += transaction

final_cf = result.items()

在这两种情况下,我只使用python中的“基本”数据结构。我使用一组来消除重复的时间,然后制作一个有序的列表。然后迭代来收集每个时间帧中发生的所有事务。