问题
Input:
pos_1= 'AVNMHDRW'
pos_2= 'KNTHDYBW'
pos_3= 'KVNGSDRB'
Trying to find all possible triplets using one item from pos_1, one from pos_2, and one from pos_3
I'm trying to figure out how to use itertools.product(*) but I'm a little confused
Ultimately, I want to create a list (or generator object) of all the different possibilities by taking one from pos_1 then one from pos_2 and then one from pos_3
Example output:
'AKK','ANV','WWB'
pos_1 stands for position one and so on for pos_2 and pos_3.
回答1:
Simple:
itertools.product(pos_1, pos_2, pos_3)
This can be iterated over; if you want a list, just pass it to list
.
What exactly is the issue?
Edit: This produces tuples of the items from each source. If you want to join them back into strings, you can do that manually when you iterate:
for a, b, c in itertools.product(pos_1, pos_2, pos_3):
do_something_with(a + b + c)
or to create the list, you can use a list comprehension:
[a + b + c for a, b, c in itertools.product(pos_1, pos_2, pos_3)]
回答2:
See this answer: In python is ther a concise way to a list comprehension with multiple iterators.
In your case:
triples = [ a+b+c for a in pos_1 for b in pos_2 for c in pos_3 ]
回答3:
You can make such generator using generator expression:
g = (v1+v2+v3 for v1 in pos_1 for v2 in pos_2 for v3 in pos_3)
来源:https://stackoverflow.com/questions/27413493/itertools-product-to-generate-all-possible-strings-of-size-3