以下代码输出:
import itertools as it
list(it.product(['A', 'T'], ['T', 'G']))
Out[230]: [('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
但是,如果列表是:
['A', '/', 'T'], ['T', '/', 'G']
['C', '|', 'T'], ['A', '|', 'C']
我想要
[('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
[('C', 'A'), ('T', 'C')]
这意味着:
list(it.product(['A', '/', 'T'], ['T', '/', 'G'])) if '/' in the list
else list(it.product(['A', '/', 'T'], ['T', '/', 'G'])) if '|' in the list
如何,在不删除 /
和 |
的情况下可以获得相同的结果,因为这是一个条件。
我认为使用索引可能会起作用并尝试了类似的方法:
list(it.product(['A', '/', 'T'], ['T', '/', 'G']).index([0,2))
还有其他几个过程,但没有帮助。
此代码是大代码的尾部,因此我不会尝试构建任何函数或删除 /
。
最佳答案
您可以应用过滤器
:
>>> from itertools import product
>>> list(filter(lambda x: '/' not in x, product(['A', '/', 'T'], ['T', '/', 'G'])))
[('A', 'T'), ('A', 'G'), ('T', 'T'), ('T', 'G')]
或预先排除它们(这次我使用与过滤器
等效的内容:条件理解):
a = ['A', '/', 'T']
b = ['T', '/', 'G']
list(product([item for item in a if item != '/'],
[item for item in b if item != '/']))
请注意,当您将其与enumerate
结合使用时,您还可以使用索引进行过滤:
list(product([item for idx, item in enumerate(a) if idx != 1],
[item for idx, item in enumerate(b) if idx != 1]))
或者,如果您对索引有简单的条件,那么对列表进行切片也是一种选择:
>>> list(product(a[:2], b[:2]))
[('A', 'T'), ('A', '/'), ('/', 'T'), ('/', '/')]
关于python - 如何对使用特定索引值的产品使用 itertools?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035665/