1

私は持っている

(('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))

そして、したいです

  (('A','E, '1', 'UTC\xb100:00'), ('B','D', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('F', '1', 'UTC+03:00'))

リストでこれを行うことができるのを見てきましたが、タープルを使用してこれを行うのを見たことはありません..これは可能ですか..?

4

5 に答える 5

0

理解を使用できますが、それでも少し複雑です。

tuples = (('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))

>>values = set(map(lambda x:x[1:3], tuples))
set([('1', 'UTC+03:00'), ('1', 'UTC\xb100:00'), ('1', 'UTC+01:00'), ('1', 'UTC+02:00')])

>>f = [[y[0] for y in tuples if y[1:3]==x] for x in values]
[['F'], ['A', 'E'], ['B', 'D'], ['C']]

>>r = zip((tuple(t) for t in f), values)
[(('F',), ('1', 'UTC+03:00')), (('A', 'E'), ('1', 'UTC\xb100:00')), (('B', 'D'), ('1', 'UTC+01:00')), (('C',), ('1', 'UTC+02:00'))]

>>result = tuple([sum(e, ()) for e in r])
(('F', '1', 'UTC+03:00'), ('A', 'E', '1', 'UTC\xb100:00'), ('B', 'D', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'))

それをまとめるには:

values = set(map(lambda x:x[1:3], tuples))
f = [[y[0] for y in tuples if y[1:3]==x] for x in values]
r = zip((tuple(t) for t in f), values)
result = tuple([sum(e, ()) for e in r])
于 2013-08-04T19:14:40.313 に答える
0

タプルでは内容を変更することはできませんが、たとえばタプルを連結して他のタプルを取得することはできます。

def process(data):
    res = []
    for L in sorted(data, key=lambda x:x[2][-5:]):
        if res and res[-1][2][-5:] == L[2][-5:]:
            # Same group... do the merge
            res[-1] = res[-1][:-2] + (L[0],) + res[-1][-2:]
        else:
            # Different group
            res.append(L)
    return res

最終結果は、タプルではなくリスト(論理的に同種のコンテンツ)のように思えますが、本当にタプルが必要な場合は、return tuple(res)代わりにできます。

于 2013-08-04T19:31:48.587 に答える