簡體   English   中英

有人可以解釋代碼嗎

[英]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
  1. 從文件中讀取一行。
  2. 如果該行為空或'\\n' ,則停止。
  3. 丟棄最后一個字符(通常為'\\n'strip()最好是IMO),由空格分隔,然后追加列表。
  4. 轉到步驟1。

而且您的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM