我知道这将返回原始数组s.t它没有前导零但我不明白这里的语法是如何实现的。
result = [0,0,1,4,2,0,3]
result = result[next((i for i, x in enumerate(result) if x != 0),
len(result)):] or [0]
让我们分解一下:
result = result[
next(
(i for i, x in enumerate(result) if x != 0),
len(result)
):
] or [0]
Python next()
函数将第一个参数作为迭代器,将第二个参数作为默认参数。当迭代器为“空”时使用默认值。因此,如果i for i, x....
的行没有产生任何结果,结果将是result[len(result):]
或只是一个空字符串。在这种情况下,or [0]
部分采取行动并返回一个单元素列表[0]
。
现在转到迭代器行。它说
i for i, x in enumerate(result) if x != 0
在英语中意味着找到i
的所有指数result
,使result[i] != 0
。并把它放到next()
,这意味着你采取了第一个这样的指数。因此,在输入列表中,您将提取非零的第一个元素的索引。然后,使用与前一段相同的逻辑,构建result[i:]
,这意味着从第一个非零元素中获取result
的子列表。
enumerate(result)
产生一个类似的迭代
[(0, 0), (1, 0), (2, 1), (3, 4), (4, 2), (5, 0), (6, 3)]
i for i, x
说第一和第二指数,返回第一。所以我们现在有一个0-6的清单。
next()
将此列表作为迭代器,如果迭代器不产生任何内容,则返回[0]
,因为or
语句。
基本上,你用[0]
(没有做任何事情)替换第一个元素,然后复制列表的其余部分。
result = [0,0,1,4,2,0,3]
a = (i for i, x in enumerate(result) if x != 0)
print(a) # <generator object <genexpr> at 0x110e075e8>
b = next(a, len(result))
print(b) # 2
c = result[b:]
print(c) # [1, 4, 2, 0, 3]
result = c or [0]
print(result) # [1, 4, 2, 0, 3]
无论如何,@ adertam和其他人已经很好地解释了这一切。对于那些看(丑陋)代码的解释的人来说,它看起来像这样:
result = [0,0,1,4,2,0,3]
i=0 # initialize the position counter
for x in result: # scan each element in the list...
if x != 0: # ...checking for non-zero elements...
break # ... break the loop if we find it...
else:
i+=1 # ... otherwise increase the counter
# i is now the index of the first non-zero element in the list
result = result[i:] # take a slice of the list, starting with the i-th element
# Note that, if i=len(result), then the slice will be an
# empty array []. That would happen, for example, if all
# the elements in the array were 0 (since we are checking
# against 0
# Hence the protection:
# If we ended up here with an empty list, assign a list with a single 0 instead
if not result:
result = [0]
print(result)
在这里看到它在https://eval.in/1101785