以下串列是我的代碼輸出的片段,你可以看到它最后列印了 [] 3 次,我想弄清楚如何擺脫它們。
我在串列理解的末尾嘗試了 "if not [], 0, '', "", element" 的組合,但似乎沒有影響。
輸出它的代碼:
list = [element.lower() for element in newline.split()]
輸出:
['do', 'ordain', 'and', 'establish', 'this', 'constitution', 'for', 'the', 'united', 'states', 'of']
['america.']
[]
[]
[]
編輯:
input_name = "file.txt"
inputFile = open(input_name,"r")
for element in input_name:
#Reads input
line = inputFile.readline()
#Removes newline using slice
newline = line[:-1]
#converts
list = [element.lower() for element in newline.split() if not '']
print(list)
檔案.txt:
為美利堅合眾國制定和制定本憲法。
檔案是一段文本
uj5u.com熱心網友回復:
出現此問題是因為您出于某種未知原因正在像這樣回圈:
for element in input_name:
..
作為input_name一個字串,這是回圈字串中的字符,這意味著您嘗試讀取八行(字串中的每個字符file.txt一個)
的長度input_name與檔案的長度無關……
uj5u.com熱心網友回復:
我認為您想要的是擺脫空串列,因此只需判斷串列本身。如果你在串列推導的末尾做某事,你只會影響串列中的元素。
如果串列為空,如 [],則為 False
temp_list = [element.lower() for element in newline.split()]
if temp_list:
print(temp_list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452124.html
