2017-04-16 37 views
-1

的名单我有一个这样的名单:如何自动分离元组

a = [(a, b), (c, i), (d, i), (e, b), (f, b), (g, i)] 

我想单独在元素b存在的元组的列表中。结果应该是这样的:

a = [[(a, b), (c, i), (d, i)], [(e, b)], [(f, b), (g ,i)]] 

有没有什么办法可以做到这一点?

+1

您的输出是否与您的输入不相同? – asongtoruin

+0

不,不,不,不,这是一个错误的抱歉 –

+0

输出如何与输入相关并不清楚。 –

回答

0

下面是一个例子:

def group_b(arr): 
    b_in_group = False 
    grouped = [] 
    group = [] 
    for tup in arr: 
     if "b" in tup: 
      if not b_in_group: 
       group.append(tup) 
       b_in_group = True 
      else: 
       if group: 
        grouped.append(group) 

       group = [tup] 
     else: 
      group.append(tup) 

    grouped.append(group) 

    return grouped 

print (group_b([("a", "b"), ("c", "i"), ("d", "i"), ("e", "b"), ("f", "b"), ("g", "i")])) 
0

如果希望能在一个单一子列表列表您的输出,你知道,将插入点始终在列表的最后一个子表。每当你看到测试数据时,附加一个新的空列表。

a = 'a' 
b = 'b' 
c = 'c' 
d = 'd' 
e = 'e' 
f = 'f' 
g = 'g' 
h = 'h' 
i = 'i' 

# input list 
in_list = [(a,b),(c,i),(d,i),(e,b),(f,b),(g,i)] 

# output 
out = [[]] 

for tpl in in_list: 
    if b in tpl: 
     # if existing list has data, push empty list on end 
     if out[-1]: 
      out.append([]) 
    out[-1].append(tpl) 

print(out)