如何将 itertools 用于使用特定索引值的产品?
How to use itertools for product using specific index value?
下面的代码输出:
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))
和其他几个过程但没有帮助。
此代码是大代码的尾部,因此我不会尝试构建任何函数或删除 /
。
您可以申请 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')]
或预先排除它们(这次我使用等同于filter
:条件理解):
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'), ('/', '/')]
下面的代码输出:
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))
和其他几个过程但没有帮助。
此代码是大代码的尾部,因此我不会尝试构建任何函数或删除 /
。
您可以申请 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')]
或预先排除它们(这次我使用等同于filter
:条件理解):
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'), ('/', '/')]