Reputation: 7255
Below code outputs:
import itertools as it
list(it.product(['A', 'T'], ['T', 'G']))
Out[230]: [('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
But, if the list is:
['A', '/', 'T'], ['T', '/', 'G']
['C', '|', 'T'], ['A', '|', 'C']
I want
[('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
[('C', 'A'), ('T', 'C')]
which means:
list(it.product(['A', '/', 'T'], ['T', '/', 'G'])) if '/' in the list
else list(it.product(['A', '/', 'T'], ['T', '/', 'G'])) if '|' in the list
How, can I get the same result without removing /
and |
because this is a condition.
I think using index might work and tried something like:
list(it.product(['A', '/', 'T'], ['T', '/', 'G']).index([0,2))
and several other process but didn't help.
This code is a tail of a big code so I am not trying to build any function or remove /
.
Upvotes: 2
Views: 195
Reputation: 152667
You could apply a filter
:
>>> from itertools import product
>>> list(filter(lambda x: '/' not in x, product(['A', '/', 'T'], ['T', '/', 'G'])))
[('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
or exclude them beforehand (this time I use the equivalent to the filter
: a conditional comprehension):
a = ['A', '/', 'T']
b = ['T', '/', 'G']
list(product([item for item in a if item != '/'],
[item for item in b if item != '/']))
Note that you can also do filters with indices when you combine it with enumerate
:
list(product([item for idx, item in enumerate(a) if idx != 1],
[item for idx, item in enumerate(b) if idx != 1]))
or if you have simple conditions to the indices then slicing the list is also an option:
>>> list(product(a[:2], b[:2]))
[('A', 'T'), ('A', '/'), ('/', 'T'), ('/', '/')]
Upvotes: 2