Problem removing leading zeros using a list comprehension best expression

后端 未结 2 1942
臣服心动
臣服心动 2021-01-29 01:12

result is a list of numbers:

result = [\'0\',\'5\',\'0\',\'1\']

I want to remove the leading zero, using the following expression:

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 01:46

    This is what you've used!

    >>> result = ['0','5','0','1']
    >>> result[next((i for i, x in enumerate(result) if x != 0), len(result)):] or [0]
    ['0', '5', '0', '1']
    

    Lets break down your list comprehension!

    [i for i,x in enumarate(result)] unpacks the enumerate(result) as i and x. That is,

    >>> enumerate(result)
    
    >>> list(enumerate(result))
    [(0, '0'), (1, '5'), (2, '0'), (3, '1')]
    >>> for i,x in enumerate(result):
    ...     print i,x
    ...
    0 0
    1 5
    2 0
    3 1
    

    Filtering the results with non zero values,

    >>> [i for i, x in enumerate(result) if x != 0]
    [0, 1, 2, 3]
    

    Now see the difference in comparing a string and an integer with x

    >>> [i for i, x in enumerate(result) if x != '0'] #list comprehension 
    [1, 3]
    
    >>> len(result)
    4
    

    next(iterator[, default])

    Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.

    That is,

    >>> next([i for i, x in enumerate(result) if x != 0], len(result)) # next takes first argument as iterator, in this example we've given a list, so exception is raised
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: list object is not an iterator
    >>> next((i for i, x in enumerate(result) if x != '0'), len(result)) #comparing with string '0' 
    1
    

    Now, we've got the first index of the list that has non zero values(lets have it as nzindex).

    With that index, we do string slicing to get all the elements after the result[nzindex:]

    This will return all elements after the index till the end.

    >>> result[next((i for i, x in enumerate(result) if x != '0'), len(result)):]
    ['5', '0', '1']
    

    If the string slicing returns an empty list(falsey result), the default value result[0] is returned!

    >>> result = ['0']
    >>> result[next((i for i, x in enumerate(result) if x != '0'), len(result)):] or result[0]
    ['0']
    

    With that said if you want to remove all the zeros in the list,

    >>> result = ['0','5','0','1']
    >>> [x for i,x in enumerate(result) if x!='0']
    ['5', '1']
    

    and if you want to remove only the leading zeros, a more efficient way would be,

    >>> next(i for i,x in enumerate(result) if x!='0')
    1
    >>> result[next(i for i,x in enumerate(result) if x!='0'):]
    ['5', '0', '1']
    

提交回复
热议问题