Python - 由多个元素组成的组(元组列表)

时间:2014-09-19 13:17:01

标签: python list sorting nested tuples

我有以下元组列表:[('platform','train','time')]

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帖子!

我如何更改代码以获得所需的输出?

1 个答案:

答案 0 :(得分: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