Assign variable in while loop condition in Python?

前端 未结 11 1567
名媛妹妹
名媛妹妹 2020-12-08 03:39

I just came across this piece of code

while 1:
    line = data.readline()
    if not line:
        break
    #...

and thought, there must

11条回答
  •  一个人的身影
    2020-12-08 04:34

    If data is a file, as stated in other answers, using for line in file will work fine. If data is not a file, and a random data reading object, then you should implement it as an iterator, implementing __iter__ and next methods.

    The next method should to the reading, check if there is more data, and if not, raise StopIteration. If you do this, you can continue using the for line in data idiom.

提交回复
热议问题