Kingle
Kingle

Reputation: 345

How to get combinations of list with values from another list?

I have a list of 3 values, two of which are string. And another list with values to replace the string:

li = [1, 'a', 'b']
li2 = [2, 3, 4]

What I thought was that I can just replace the string with the second list and call itertools.combinations() on it:

li = [li2 if isinstance(x, str) else x for x in li]
li = [1, [2, 3, 4], [2, 3, 4]]
combo = list(itertools.combinations(li, 3)

But it just gives me a tuple of the same list back. What I wanted was something like [1, 2, 3], [1, 2, 4], [1, 3, 4]. I tried permutations also but it didn't help. How can I get all combinations of values from two lists, keeping value from first list in place?

Upvotes: 0

Views: 147

Answers (2)

Francisco
Francisco

Reputation: 11496

import itertools

li = [1, 'a', 'b']
li2 = [2, 3, 4]

def combinations_letters(li, li2):
    li = list(li)
    indexes = [i for i, x in enumerate(li) if isinstance(x, str)]
    for comb in itertools.combinations(li2, r=len(indexes)):
        for index, c in zip(indexes, comb):
            li[index] = c
        yield tuple(li)

print list(combinations_letters(li, li2))

This outputs:

[(1, 2, 3), (1, 2, 4), (1, 3, 4)]

What this does is find the indexes of all the strings in li, and replace them with the output of itertools.permutations.

Upvotes: 3

GaryMBloom
GaryMBloom

Reputation: 5700

It's all about understanding the algorithm. It sounds to me like you have a first list with some numbers and some letters in it, and a second list with more numbers than there are letters in the first list. Then you have to go through and replace the letters in the first list with all the possible combinations of that many numbers in the second list. This sounds like the problem you're trying to solve. If you solve this problem, it doesn't matter how many letters or numbers are in the first list, as long as there are more numbers in the second list than letters in the first.

The first thing you need to do is see how many letters there are in your first list. That will be the length of the combinations you extract from the second list. Then, once you have generated that list of all possible combinations from the second list, you would go through the first list, making the required substitutions.

If you do this, then your code will be able to handle any input changes.

Upvotes: 0

Related Questions