0

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

基本上,我想从这个开始:

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

至:

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

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

4

3 回答 3

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())
于 2013-10-10T18:03:53.573 回答
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是内置模块,请勿将其用作变量名。

于 2013-10-10T17:54:07.990 回答
0

It isn't my greatest work in style, but it fits your needs.

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)

Another approach is using a 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()

In both cases i used just the "basic" data structures in python. I used a set to eliminate duplicated time, and then made a ordered list of it. Then a iteration to collect all transactions that happened in each time frame.

于 2013-10-10T18:01:30.603 回答