如何在 python3 中的列表理解中使用下一个迭代器来获取没有任何前导零的列表

How to use next iterator within a list comprehension in python3 to get a list without any leading zeroes

尝试使用 next() 从数组列表中删除所有前导零并在列表推导中进行枚举。遇到了以下有效的代码。谁能解释清楚代码的作用

示例:result = [0,0,1,2,0,0,3] returns result = [1,2,0,0,3]

已编辑* - 代码只是删除了前导零

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

所以让我们从内到外解压代码。

(i for i, x in enumerate(result) if x != 0) 是所有非零值索引的生成器。

next((i for i, x in enumerate(result) if x != 0), len(result)) returns 生成器的第一个值(因此第一个非零值的索引)。 len(result)是默认值,如果生成器没有return任何值。所以我们也可以将这个结果提取到一个新变量中。

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

最后一步是简单的列表理解,只从列表中获取索引等于或高于给定索引的值。

Trying to remove all the leading zeroes from a list of array using next() and enumerate within a list comprehension.

您是否有义务使用 next()enumerate() 和列表理解?另一种方法:

from itertools import dropwhile
from operator import not_ as is_zero

result = dropwhile(is_zero, [0, 0, 1, 2, 0, 0, 3])

print(*result)

输出

% python3 test.py
1 2 0 0 3
%

我们可以潜在地解释原始代码:

result = [0, 0, 1, 2, 0, 0, 3]

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

将其分解并执行:

enumerate(result)  # list of indexes and values [(i0, x0), (i1, x1), ...]
[(0, 0), (1, 0), (2, 1), (3, 2), (4, 0), (5, 0), (6, 3)] 

[i for i, x in enumerate(result)]  # just the indexes
[i for i, x in [(0, 0), (1, 0), ..., (5, 0), (6, 3)]]  # what effectively happens
[0, 1, 2, 3, 4, 5, 6]

[i for i, x in enumerate(result) if x != 0]  # just the indexes of non-zero values
[2, 3, 6]

# not needed with this example input, used to make an all
# zero list like [0, 0, ..., 0] return the empty list []
len(result)  
7

# pull off the first element of list of indexes of non-zero values
next((i for i, x in enumerate(result) if x != 0), len(result))
next(iter([2, 3, 6]), 7)  # what effectively happens 
2

result[next((i for i, x in enumerate(result) if x != 0), len(result)):]  # slice
result[2:]  # what effectively happens
[1, 2, 0, 0, 3]