Removing an element from a list based on a predicate

前端 未结 9 1406
伪装坚强ぢ
伪装坚强ぢ 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:12

    Any reason for duplicating the entire list? How about:

    >>> def pred(item, haystack="XN"):
    ...     return any(needle in item for needle in haystack)
    ...
    >>> lst = ['AAT', 'XAC', 'ANT', 'TTA']
    >>> idx = 0
    >>> while idx < len(lst):
    ...     if pred(lst[idx]):
    ...         del lst[idx]
    ...     else:
    ...         idx = idx + 1
    ...
    >>> lst
    ['AAT', 'TTA']
    

    I know that list comprehensions are all the rage these days, but if the list is long we don't want to duplicate it without any reason right? You can take this to the next step and create a nice utility function:

    >>> def remove_if(coll, predicate):
    ...     idx = len(coll) - 1
    ...     while idx >= 0:
    ...         if predicate(coll[idx]):
    ...             del coll[idx]
    ...         idx = idx - 1
    ...     return coll
    ...
    >>> lst = ['AAT', 'XAC', 'ANT', 'TTA']
    >>> remove_if(lst, pred)
    ['AAT', 'TTA']
    >>> lst
    ['AAT', 'TTA']
    

提交回复
热议问题