gpt4 book ai didi

Python - 多个元素的groupby(元组列​​表)

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:31 28 4
gpt4 key购买 nike

我有以下元组列表:[('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发布!

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

最佳答案

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

关于Python - 多个元素的groupby(元组列​​表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934883/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com