2017-04-13 291 views
2

比方說,我有元組的名單如下列表:列表和添加第二個元素

tuples = [ 
      [ 
       ('2017-04-11', '2000000.00'), 
       ('2017-04-12', '1000000.00'), 
       ('2017-04-13', '3000000.00') 
      ], 
      [ 
       ('2017-04-12', '472943.00'), 
       ('2017-04-13', '1000000.00') 
      ] 
      # ... 
     ] 

我怎麼會去將它們分組基於關閉的第一個元素(日期)並添加其他元素。

比如我想是這樣的:

tuples = [('2017-04-11', '2000000.00'), ('2017-04-12', '1472943.00'), ('2017-04-13', '4000000.00')], 
+0

所以,你發佈你的輸入和你預期的結果。但是,你自己在解決問題的方法在哪裏?請發佈您的代碼並告訴我們您卡在哪裏。 –

+0

通過看到預期的產出不明白。但是: 將羣組標識設爲密鑰並創建一個字典。 '{「group-identity」,[your-list-mentioned-above]}'。使用python以這種格式創建數據。這是你在找什麼? – Haranadh

+0

我已經提出了一個問題,因爲我嘗試了很多解決方案,無法實現。我嘗試了map,itertools.izip_longest沒有任何運氣@ mpf82 –

回答

3

使用itertools.chain.from_iterableitertools.groupbysum功能的解決方案:

import itertools, operator 

tuples = [ 
     [('2017-04-11', '2000000.00'), ('2017-04-12', '1000000.00'), ('2017-04-13', '3000000.00')], 
     [('2017-04-12', '472943.00'), ('2017-04-13', '1000000.00')] 
     ] 

result = [(k, "%.2f" % sum(float(t[1]) for t in g)) 
      for k,g in itertools.groupby(sorted(itertools.chain.from_iterable(tuples)), operator.itemgetter(0))] 

print(result) 

輸出:

[('2017-04-11', '2000000.00'), ('2017-04-12', '1472943.00'), ('2017-04-13', '4000000.00')] 
0

我的路是將嵌套列表轉換爲平面列表並重復它:

t = [ 
     [('2017-04-11', '2000000.00'), ('2017-04-12', '1000000.00'), ('2017-04-13', '3000000.00')], 
     [('2017-04-12', '472943.00'), ('2017-04-13', '1000000.00')] 
     ] 
a={} 

for i,j in sum(t,[]): 
    a[i]=a[i]+float(j) if i in a else float(j) 

print(a) 

輸出:

{'2017-04-11': 2000000.0, '2017-04-13': 4000000.0, '2017-04-12': 1472943.0} 

如果你想有一個列表,你可以使用[(k,v) for k,v in a.items()])

0

壓扁列表,然後利用defaultdict:

from collections import defaultdict 

flattened_tuples = [item for sublist in tuples for item in sublist] 

result = defaultdict(float) 
for date, value in flattened_tuples: 
    result[date] += float(value) 
print(result) 

回報 {'2017-04-11': 2000000.0, '2017-04-12': 1472943.0, '2017-04-13': 4000000.0}

1

首先,扁一個元組出來的元組的列表的列表的列表,然後用itertools.groupby

import itertools 
import operator 

lists = [ 
     [('2017-04-11', '2000000.00'), ('2017-04-12', '1000000.00'), ('2017-04-13', '3000000.00')], 
     [('2017-04-12', '472943.00'), ('2017-04-13', '1000000.00')] 
     ] 

# Step 1: Flat a list of tuples out of a list of lists of tuples 
list_tuples = [t for sublist in lists for t in sublist] 
''' 
[('2017-04-11', '2000000.00'), ('2017-04-12', '1000000.00'), ('2017-04-13', '3000000.00'), ('2017-04-12', '472943.00'), ('2017-04-13', '1000000.00')] 
''' 

# Step 2: Groupby 
results = list() 

for key, group in itertools.groupby(sorted(list_tuples), operator.itemgetter(0)): 
    s = sum(float(t[1]) for t in group) 
    results.append((key, s)) 

print(results) 
#[('2017-04-11', 2000000.0), ('2017-04-12', 1472943.0), ('2017-04-13', 4000000.0)] 
相關問題