Itertools是一個Python模塊,提供可在迭代器上工作的各種函數,以產生複雜的迭代器。它使代碼更快,內存效率更高,因此我們看到了更好的性能。此模塊既可以單獨使用,也可以結合使用以形成迭代器代數。
注意:有關更多信息,請參閱Python Itertools。
Dropwhile()
的dropwhile()
Python函數僅在func
。在參數返回中false
首次。
用法:
dropwhile(func, seq):
範例1:
# Python code to demonstrate the working of
# dropwhile()
# Function to be passed
# as an argument
def is_positive(n):
return n > 0
value_list =[5, 6, -8, -4, 2]
result = list(itertools.dropwhile(is_positive, value_list))
print(result)
輸出:
[-8, -4, 2]
範例2:
# Python code to demonstrate the working of
# dropwhile()
import itertools
# initializing list
li = [2, 4, 5, 7, 8]
# using dropwhile() to start displaying after condition is false
print ("The values after condition returns false:", end ="")
print (list(itertools.dropwhile(lambda x:x % 2 == 0, li)))
輸出:
The values after condition returns false:[5, 7, 8]
注:本文由純淨天空篩選整理自dakshaladia大神的英文原創作品 Python – Itertools.dropwhile()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。