Biotechgeek Biotechgeek - 1 month ago 7
Python Question

How to pair every element in a list with the other in a list of lists in Python?

I have a list that looks like:

results=[['000', '111', '000'],
['110', '000', '101'],
['000', '000', '000']]


I need to pair every element in the sublist with every other element (except itself). Desired Output:

[[['000', '111'], ['000', '000'], ['111', '000']],
[['110', '000'], ['110', '101'], ['000', '101']],
[['000', '000'], ['000', '000'], ['000', '000']]]


Code Attempted:

samplefinal =[]
for sub_list in results:
for i, j in combinations(range(len(sub_list)), 2):
out = ['', '']
sample3 = []
for pair in zip(sub_list[i], sub_list[j]):
if '-' not in pair:
out[0] += pair[0]
out[1] += pair[1]
sample3.append(out)
samplefinal.append(sample3)
print samplefinal

Output: [[['111', '000'], ['111', '000'], ['111', '000']], [['000', '101'], ['000', '101'], ['000', '101']], [['000', '000'], ['000', '000'], ['000', '000']]]


I am not quite sure where I may be going wrong. The indices and range work fine, any suggestions?

Answer

It seems to me like you want every combination of size 2 of your sublists. Use itertools:

>>> import itertools
>>> results=[['000', '111', '000'], ['110', '000', '101'], ['000', '000', '000']]
>>> [[list(comb) for comb in itertools.combinations(sub,2)] for sub in results]
[[['000', '111'], ['000', '000'], ['111', '000']], [['110', '000'], ['110', '101'], ['000', '101']], [['000', '000'], ['000', '000'], ['000', '000']]]

And using pretty-print to make things clear:

>>> from pprint import pprint
>>> combos = [[list(comb) for comb in itertools.combinations(sub,2)] for sub in results]
>>> pprint(combos)
[[['000', '111'], ['000', '000'], ['111', '000']],
 [['110', '000'], ['110', '101'], ['000', '101']],
 [['000', '000'], ['000', '000'], ['000', '000']]]
>>>