python - 如何对使用特定索引值的产品使用 itertools?

标签 python list product indexof python-itertools

以下代码输出:

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/

相关文章:

wordpress - 如何仅重定向给定日期的产品

cordova - 我可以使用PhoneGap嵌入ASP.Net网站来制作Android应用程序吗?

python - 将包含用于 Python 变量赋值的文本的字符串转换为实际变量

Python 列表 - L1+=[5] 和 L1 = L1+[5] 的不同结果

python - 无法从 CSV 中提取独特的单词

python - 列表继承 : "extend" vs "+" vs "+="

mysql - 按订单存储产品 - 下订单后产品将被删除

Python 3.5 类型提示动态生成的实例属性

python - astropy.convolution.convolve 返回 nan 值

python - 如何在python中读取json嵌入ini配置文件