[英]can someone explain the code
有人可以解釋該代碼如何工作:我對while循環不熟悉
line = file.readline()
L1=[]
while line != '' and line != '\n':
line = line[:-1].split()
L1.append(line)
line = file.readline()
return L1
我可以用for循環嗎? 是嗎:
for line in file.readline():
if line !='' and line !='\n':
line = line[:-1].split()
L1.append(line)
return L1
'\\n'
,則停止。 '\\n'
, strip()
最好是IMO),由空格分隔,然后追加列表。 而且您的for
循環的問題在於它不會在空或'\\n'
停止
首先閱讀以下內容: http : //wiki.python.org/moin/WhileLoop這將向您介紹while循環。
while循環是在條件為真時將繼續的循環,
x = 0
while x < 10:
print(x)
x = x + 1
print("finished")
將打印輸出0 1 2 3 4 5 6 7 8 9 finished
當x == 10 0 1 2 3 4 5 6 7 8 9 finished
時,循環將結束,並且將顯示單詞“完成”。
幾乎。 第一個示例在讀取匹配''
或'\\n'
的行時將停止循環。 您可以將其簡化為:
from itertools import takewhile
[x.strip() for x in takewhile(lambda x: x not in ['', '\n'], file.readlines())]
這將存儲文件的每一行,直到在新數組中找到''
或'\\n
為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.