Problem removing leading zeros using a list comprehension best expression

后端 未结 2 1976
臣服心动
臣服心动 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:47

    The expression looks for the first non-zero in the list, returning the remaining list. More detail at the bottom.

    ANALYSIS

    However, you have characters: there is no integer 0 in your list. Therefore, the expression merely returns the original list.

    SOLUTION

    If you want it to work on characters, simply include the quotation marks required:

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

    This give you:

    Original code:

    >>> 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']
    

    Adapted to strings / characters:

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

    EXPRESSION LOGIC

    The critical clauses are in the deepest part of the comprehension:

    (i for
        i, x in enumerate(result)
            if x != '0')
    

    In the enumerate clause, i, x iterates through the list indices and its contents: (0, '0'), (1, '5'), etc.

    The if checks for zero characters; it filters out all zeroes. The i for part doesn't get any i value until the inner clause finds a non-zero.

    At that point, the outer next operator takes over: it takes the first index of a non-zero and returns that to the slice operator (note that colon at the end), which returns the remainder of the list.

    As pault already mentioned, the len at the end is the default value: if your zero filter disqualifies the entire list (all zeroes), then the comprehension returns len(result) to next. This mean that next will return the list length, and your result slicing returns an empty list. Now your or expression has a "Falsy" value in the first operand; it returns the second operand, the list ['0'].

提交回复
热议问题