【问题标题】:How to use itertools for product using specific index value?如何将 itertools 用于使用特定索引值的产品?
【发布时间】:2017-02-04 01:53:28
【问题描述】:

以下代码输出:

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))

和其他几个过程,但没有帮助。

这段代码是大代码的尾部,所以我不想构建任何函数或删除/

【问题讨论】:

    标签: python list product indexof itertools


    【解决方案1】:

    你可以申请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'), ('/', '/')]
    

    【讨论】:

    • 我稍微更新了条件。能否请您再看看问题。
    • 你能澄清一下实际条件是什么吗?我的印象是我理解你的意思 - 但鉴于你的新例子 (['C', '|', 'T'], ['A', '|', 'C']):那里的规则是什么?
    • 你的意思是:[items for items in zip(['A', '|', 'T'], ['T', '|', 'G']) if '|' not in items]?
    • 但现在这是一个完全不同的问题! applymap 不等同于 pythons 过滤器,因此它甚至与答案无关。你能再开一个问题吗?猜一猜.applymap(lambda c: ','.join('g'.join(t) for t in it.product(*c) if '/' not in t)))
    • .applymap(lambda c: ','.join('g'.join(t) for t in it.product(*c) if '/' not in t) if '/' in c else ','.join('g'.join(t) for t in zip(*c)))?还有另一个建议:请提出一个新问题。您可以明确地链接到该问题和那里的另一个问题,但如果您每个问题只问一个问题,您可能会得到更好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多