2016-11-24 6 views
0

私は別のタプルを作成して、空のリストに追加されます。pythonでタプルのリストにgroupbyを適用する方法は?私の機能で

tup = (pattern,matchedsen) 
matchedtuples.append(tup) 

パターンは正規表現の形式を持っています。例えば

:私は道以下でmatchedtuplesgroupby()を適用するために探しています

matchedtuples = [(p1, s1) , (p1,s2) , (p2, s5)] 

そして、私はこの結果を探しています:私はグループを持つことになり、このように、

result = [ (p1,(s1,s2)) , (p2, s5)] 

ので、同じパターンの文章のこれどうやってするの?

答えて

0

出力が必要な場合は、手動でグループをループしてリストを作成する必要があります。

まず、もちろん、matchedtuplesリストはitemgetterで、並べ替え、それをソートされていない場合:

from operator import itemgetter as itmg 

li = sorted(matchedtuples, key=itmg(0)) 

その後、結果をループがgroupbyから供給されるとの大きさに基づいてリストrに追加グループ:

r = [] 
for i, j in groupby(matchedtuples, key=itmg(0)): 
    j = list(j) 
    ap = (i, j[0][1]) if len(j) == 1 else (i, tuple(s[1] for s in j)) 
    r.append(ap) 
0

あなたの質問に対する私の答えは、あなたが与えたのと同じ出力を使用して印刷する任意の入力構造に対して機能します。そして、私はitertoolsモジュールからのみgroupby使用します。

# Let's suppose your input is something like this 
a = [("p1", "s1"), ("p1", "s2"), ("p2", "s5")] 

from itertools import groupby 

result = [] 

for key, values in groupby(a, lambda x : x[0]): 
    b = tuple(values) 
    if len(b) >= 2: 
     result.append((key, tuple(j[1] for j in b))) 
    else: 
     result.append(tuple(j for j in b)[0]) 

print(result) 

出力:

[('p1', ('s1', 's2')), ('p2', 's5')] 

、あなたの入力に複数の値を追加する場合、同じソリューションの仕事:

# When you add more values to your input 
a = [("p1", "s1"), ("p1", "s2"), ("p2", "s5"), ("p2", "s6"), ("p3", "s7")] 

from itertools import groupby 

result = [] 

for key, values in groupby(a, lambda x : x[0]): 
    b = tuple(values) 
    if len(b) >= 2: 
     result.append((key, tuple(j[1] for j in b))) 
    else: 
     result.append(tuple(j for j in b)[0]) 

print(result) 

出力:

[('p1', ('s1', 's2')), ('p2', ('s5', 's6')), ('p3', 's7')] 

さて、あなたはあなたの入力構造を変更した場合:

# Let's suppose your modified input is something like this 
a = [(["p1"], ["s1"]), (["p1"], ["s2"]), (["p2"], ["s5"])] 

from itertools import groupby 

result = [] 

for key, values in groupby(a, lambda x : x[0]): 
    b = tuple(values) 
    if len(b) >= 2: 
     result.append((key, tuple(j[1] for j in b))) 
    else: 
     result.append(tuple(j for j in b)[0]) 

print(result) 

出力:また

[(['p1'], (['s1'], ['s2'])), (['p2'], ['s5'])] 

、あなたの新しい入力構造に多くの値を追加する場合、同じソリューションの仕事:

# When you add more values to your new input 
a = [(["p1"], ["s1"]), (["p1"], ["s2"]), (["p2"], ["s5"]), (["p2"], ["s6"]), (["p3"], ["s7"])] 

from itertools import groupby 

result = [] 

for key, values in groupby(a, lambda x : x[0]): 
    b = tuple(values) 
    if len(b) >= 2: 
     result.append((key, tuple(j[1] for j in b))) 
    else: 
     result.append(tuple(j for j in b)[0]) 

print(result) 

出力:

[(['p1'], (['s1'], ['s2'])), (['p2'], (['s5'], ['s6'])), (['p3'], ['s7'])] 

Ps:このコードをテストし、他の種類の入力で破損した場合はお知らせください。

関連する問題