Removing an element from a list based on a predicate

前端 未结 9 1387
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 12:36

I want to remove an element from list, such that the element contains \'X\' or \'N\'. I have to apply for a large genome. Here is an example:

9条回答
  •  臣服心动
    2021-01-18 13:03

    Another not fastest way but I think it reads nicely

    >>> [x for x in ['AAT','XAC','ANT','TTA'] if not any(y in x for y in "XN")]
    ['AAT', 'TTA']
    
    >>> [x for x in ['AAT','XAC','ANT','TTA'] if not set("XN")&set(x)]
    ['AAT', 'TTA']
    

    This way will be faster for long codons (assuming there is some repetition)

    codon = ['AAT','XAC','ANT','TTA']
    def pred(s,memo={}):
        if s not in memo:
            memo[s]=not any(y in s for y in "XN")
        return memo[s]
    
    print filter(pred,codon)
    

    Here is the method suggested by James Brooks, you'd have to test to see which is faster for your data

    codon = ['AAT','XAC','ANT','TTA']
    def pred(s,memo={}):
        if s not in memo:
            memo[s]= not set("XN")&set(s)
        return memo[s]
    
    print filter(pred,codon)
    

    For this sample codon, the version using sets is about 10% slower

提交回复
热议问题