How do I make all combinations of elements in an array?

I have a list. It contains lists of x, each with y elements. I want to bind each element to all other elements just once (a, b = b, a)

EDIT: This has been criticized as being too vague. Therefore, I will describe the story. My function generates random equations and uses genetic methods, mutates and crosses them, choosing for fitness. After several iterations, it returns a list of 12 objects, sorted by the suitability of their 'equation' attribute. Using the "parallel python" module to execute this function 8 times, a list is returned containing 8 lists of 12 objects (each with an equation attribute). Now, in each list, 12 objects have crossed themselves with each other. I want to cross every object in a list with all other objects in all other lists, but not with objects inside it of its own list that it has already crossed. (Hmm!)

+2


source to share


3 answers


itertools.product

- your friend.

about removing duplicates, try with a set of sets.

Now it's a little clearer what you want:



import itertools

def recombinate(families):
    "families is the list of 8 elements, each one with 12 individuals"
    for fi, fj in itertools.combinations(families, 2):
        for pair in itertools.product(fi, fj):
            yield pair

      

basically, take all 2-combinations of families (from those that are produced in parallel) and for each pair of families, output all pairs of elements.

+7


source


You did not understand what you need. It looks like itertools should have what you need. Perhaps what you want is itertools.combinations of itertools.product from the lists in your big list.



@fortran: you can't have a set of sets. You may have a bunch of freezones, but depending on what duplication really means here, this may not be what you want.

+1


source


First of all, please don't call this an "array". You are using a list of lists. In Python, an array is another type of data structure provided by the array module.

Also, your application looks suspiciously like a matrix. If you really do matrix manipulation, you should look into the Numpy package.

At first glance, your problem sounds like something that the zip () or itertools.izip () function can solve. You should definitely read the docs for the itertools module because it has various list manipulations and they will run faster than anything you could write in Python.

0


source







All Articles