Monica Monica - 1 year ago 102
Python Question

Creating pairs of objects in a list

I have a list of objects:

object_list = ['distance', 'alpha1', 'alpha2', 'gamma']

I want to obtain a new list with a pair combination of those objects, such as:

new_list = [ ['distance', 'alpha1'], ['distance', 'alpha2'], ['distance', 'gamma'],['alpha1', 'alpha2'], [ 'alpha1', 'gamma'] ... ]

Generally I will obtain 24 sublists(cases).

Answer Source

Have a look at itertools - itertools.combinations seems to be the thing you are looking for. use like

import itertools
object_list = ['distance', 'alpha1', 'alpha2', 'gamma']
new_list = list(itertools.combinations(object_list, 2))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download