python 2.7 - Groupby match into list of lists -
i have 2 lists have matching elements. example:
l1 = [a, b] l2 = [1_a, i_x, i_y, 2_a, x_b, y_b, z_b]
i wish group matching factors new list following:
match_grouplist = [[1_a, 2_a],[x_b, y_b, z_b]]
i tried,
pull = []; tmp = [] entry in range(len(l1)): spp = l[entry] ele in l2: if ele.split("_")[1] == spp: tmp.append(ele) pull.extend(tmp)
it produces list. can suggest how make list of list ?
thanks in advance,
ap
here solution using list comprehensions :
[ [e2 e2 in l2 if e2.endswith('_'+e1)] e1 in l1 ]
this means each element e1 of l1 elements of l2 end _e1, , return it.
the result [['1_a', '2_a'], ['x_b', 'y_b', 'z_b']]
Comments
Post a Comment