2014-09-19 44 views
1

,我有以下的元組的列表:[('platform','train','time')]Python的 - 多個元素的GROUPBY(數組列表)

travel= [(2,5,'09-19-2014'),(2,3,'07-19-2014'),(1,5,'06-19-2014'),(2,3,'04-19-2014').(1,5,'01-19-2014'),(1,2,'02-19-2014')] 

,我想我的輸出是這樣的:

Platform 1: train 2: 02-19-2014, train 5: 02-19-2014, 06-19-2014 
Platform 2: train 3: 04-19-2014, 07-19-2014 train 5: 09-19-2014 

到目前爲止,我只得到:

Platform 1: train 2, train 5 
Platform 2: train 3, train 5 

使用此代碼:

 for key, group in groupby(travel, lambda x: x[0]): 
      listOfThings = " , ".join(["%s" % thing[1] for thing in group]) 
      print "Platform " + key + ": " + listOfThings 

靈感來自this發表!

我將如何更改代碼才能獲得所需的輸出?

+0

無論是第一排序平臺編號列表或使用字典,平臺號碼作爲關鍵。 – 2014-09-19 13:20:47

回答

5

groupby要求傳遞給它的iterable按照下面的代碼進行排序。平臺第一組groupby。然後第二個groupby被用來按照火車分組時間。

from itertools import groupby 

travel= [(2,5,'09-19-2014'),(2,3,'07-19-2014'),(1,5,'06-19-2014'),(2,3,'04-19-2014'),(1,5,'01-19-2014'),(1,2,'02-19-2014')] 

for platform, g1 in groupby(sorted(travel), lambda t: t[0]): 
    print 'Platform {}: '.format(platform), 
    trains = [] 
    for train, times in groupby(sorted(g1), lambda t: t[1]): 
     trains.append('train {}: {}'.format(train, ', '.join(time[2] for time in times))) 
    print ', '.join(trains) 

輸出

Platform 1: train 2: 02-19-2014, train 5: 01-19-2014, 06-19-2014 
Platform 2: train 3: 04-19-2014, 07-19-2014, train 5: 09-19-2014 
+0

謝謝,這個作品:) – Sepi 2014-09-27 17:47:13

+1

@Sepi那麼你爲什麼不接受它作爲正確的答案:) – confused00 2014-10-23 10:01:32

相關問題