-5

Python 2.6 にタプルがあります。詳細は以下のとおりです。

mylist = [
['20120903', 'melon', 'shelf1', '05:31', '08:01'],
['20120903', 'melon', 'shelf1', '05:31', '14:01'],
['20120903', 'melon', 'shelf1', '05:31', '23:59'],
['20120903', 'melon', 'shelf1', '10:18', '14:01'],
['20120903', 'melon', 'shelf1', '10:18', '23:59'],
['20120904', 'melon', 'shelf1', '00:00', '14:02'],
['20120904', 'melon', 'shelf1', '05:32', '14:02'],
['20120903', 'apple', 'shelf5', '05:34', '14:02'],
['20120903', 'apple', 'shelf5', '05:34', '23:59'],
['20120904', 'apple', 'shelf5', '00:00', '14:02'],
['20120904', 'apple', 'shelf5', '05:33', '14:02']]

以下のような結果を取得したいと思います(列0、1、2、3が同一の場合、4番目の列の最小値+列0、1、2、4が同一の場合、最大値を取ります3列目):

result = [
['20120903', 'melon', 'shelf1', '05:31', '08:01'],
['20120903', 'melon', 'shelf1', '10:18', '14:01'],
['20120904', 'melon', 'shelf1', '05:32', '14:02'],
['20120903', 'apple', 'shelf5', '05:34', '14:02'],
['20120904', 'apple', 'shelf5', '05:33', '14:02']]

Ashwini Chaudhary のおかげで、彼のコードを少し修正したところ、次のようになりました。

from itertools import groupby

mylist = [
['20120903', 'melon', 'shelf1', '05:31', '08:01'],
['20120903', 'melon', 'shelf1', '05:31', '14:01'],
['20120903', 'melon', 'shelf1', '05:31', '23:59'],
['20120903', 'melon', 'shelf1', '10:18', '14:01'],
['20120903', 'melon', 'shelf1', '10:18', '23:59'],
['20120904', 'melon', 'shelf1', '00:00', '14:02'],
['20120904', 'melon', 'shelf1', '05:32', '14:02'],
['20120903', 'apple', 'shelf5', '05:34', '14:02'],
['20120903', 'apple', 'shelf5', '05:34', '23:59'],
['20120904', 'apple', 'shelf5', '00:00', '14:02'],
['20120904', 'apple', 'shelf5', '05:33', '14:02']]

step1 = []
for k1, g1 in groupby(mylist, key=lambda x1: (x1[0], x1[1], x1[2], x1[3])):
    step1.append((min(g1, key=lambda x1: map(int, x1[4].split(':')))))

step2 = []
for k2, g2 in groupby(step1, key=lambda x2: (x2[0], x2[1], x2[2], x2[4])):
    step2.append((max(g2, key=lambda x2: map(int, x2[3].split(':')))))

for result in step2:
    print result
4

1 に答える 1