![](/img/trans.png)
[英]Python: moving all elements greater than 0 to left and right in numpy array
[英]python find the num in list greater than left and right
問題是使用迭代器從列表中查找大於左右數字的數字
例如,select([0,1,0,2,0,3,0,4,0])返回[1,2,3,4]
我的第一次嘗試是
def select(iterable):
answer = []
it = iter(iterable)
try:
v2 = next(it)
while True:
v1,v2= v2,next(it)
if v2>v1 and v2>next(it):
answer.append(v2)
except StopIteration:
pass
return answer
此代碼失敗。 我認為while循環中的next(it)將是相同的迭代器,但next()仍會迭代代碼中的下一個。
然后我將代碼更改為以下代碼,它可以工作。
try:
v1,v2,v3 = next(it),next(it),next(it)
while True:
if v2>v1 and v2>v3:
answer.append(v2)
v1,v2,v3 = v2,v3,next(it)
except StopIteration:
pass
有人可以解釋這里有什么區別嗎?
第一個代碼段存在兩個問題:
next(it)
,它都會推進迭代器。 如果要多次訪問返回值,則必須存儲它。 再次調用next(it)
不會這樣做。 它將再次推進迭代器。 即使第一點不是問題,但以下問題仍然存在:
if v2>v1 and v2>next(it):
這里的問題是短路評估 。 取決於v2>v1
,這可能會或可能不會使迭代器前進。
錯誤在於此行:
if v2>v1 and v2>next(it):
您的調用next(it),但是您不存儲返回值。 您只需將其與v2進行比較即可。 因此,該值將被跳過。
編輯:
順便說一句,如果您比較多個值,則以下比較會更簡潔:
if v1 < v2 > v3:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.