Tại sao list(next(iter(())) for _ in range(1))
trả lại danh sách trống thay vì nâng cao StopIteration
?Tại sao danh sách (tiếp theo (lặp (())) cho _ trong phạm vi (1)) == []?
>>> next(iter(()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> [next(iter(())) for _ in range(1)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> list(next(iter(())) for _ in range(1)) # ?!
[]
Điều tương tự cũng xảy ra với một chức năng tùy chỉnh mà tăng một cách rõ ràng StopIteration
:
>>> def x():
... raise StopIteration
...
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
StopIteration
>>> [x() for _ in range(1)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
StopIteration
>>> list(x() for _ in range(1)) # ?!
[]
Wow, tôi thực sự thích câu trả lời trong câu hỏi "trùng lặp" gốc! – wheaties
Đây là lỗi, nó đang được giải quyết với [PEP 479] (http://legacy.python.org/dev/peps/pep-0479/) trong đó 'StopIteration' sẽ được chuyển đổi thành' RuntimeError' để danh sách không dừng lặp lại không chính xác như bạn mong đợi. –
@ TadhgMcDonald-Jensen vui lòng cho câu trả lời đó để tôi có thể bỏ phiếu. – wheaties