有沒有一種簡單的方法可以測試生成器是否沒有任何東西,例如peek,hasNext,isEmpty等?
3 回答

紅糖糍粑
TA貢獻1815條經(jīng)驗 獲得超6個贊
建議:
def peek(iterable):
try:
first = next(iterable)
except StopIteration:
return None
return first, itertools.chain([first], iterable)
用法:
res = peek(mysequence)
if res is None:
# sequence is empty. Do stuff.
else:
first, mysequence = res
# Do something with first, maybe?
# Then iterate over the sequence:
for element in mysequence:
# etc.
添加回答
舉報
0/150
提交
取消