可以產生具有單號的元組無論是在列表理解或發電機exrpession的False
位置或True
位置:
>>> [(e,0) if c=='False' else (0,e) for e, c in zip(rts, inControl)]
[(379, 0), (396, 0), (0, 480), (0, 443), (365, 0), (0, 280), (487, 0), (0, 446), (0, 350), (367, 0), (405, 0), (391, 0), (484, 0), (359, 0), (367, 0), (0, 305), (359, 0), (0, 479), (436, 0), (333, 0)]
你然後可以歸納一系列的元組與reduce
:
>>> reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), (((e,0) if c=='False' else (0,e) for e, c in zip(rts, inControl))))
(5128, 2783)
您實際上可以使用False
個True
布爾訪問元組:
>>> t=reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), ((e if c=='False' else 0, e if c=='True' else 0) for e, c in zip(rts, inControl)))
>>> t[False]
5128
>>> t[True]
2783
或者,你可以使用map
如果這更有意義,您:
>>> map(sum, zip(*((e,0) if c=='False' else (0,e) for e, c in zip(rts, inControl))))
[5128, 2783]
或者,你可以創建一個字典與金額:
>>> dict(zip([False, True], map(sum, zip(*[(e,0) if c=='False' else (0,e) for e, c in zip(rts, inControl)]))))
{False: 5128, True: 2783}
如果你有大熊貓,一個偉大的方式做,這是與.groupby()
和sum
:
>>> import pandas as pd
>>> df=pd.DataFrame({'rts':rts, 'inControl':inControl})
>>> df
inControl rts
0 False 379
1 False 396
2 True 480
3 True 443
4 False 365
5 True 280
6 False 487
7 True 446
8 True 350
9 False 367
10 False 405
11 False 391
12 False 484
13 False 359
14 False 367
15 True 305
16 False 359
17 True 479
18 False 436
19 False 333
>>> df.groupby(inControl).sum()
rts
False 5128
True 2783
查找到'itertools',特別到了'groupby'。請參閱該文檔[這裏](https://docs.python.org/2/library/itertools.html#itertools.groupby) –
@TammoHeeren:爲'groupby':「一般情況下,迭代需求已經在整理同樣的關鍵功能「。需要在這裏對元組進行排序。 –
@ Jean-FrançoisFabre好評。你絕對正確。這裏應該在'inControl'上進行排序。 –