這個簡單的程序從文本文件中讀取單詞列表,并將子列表寫入另一個文件,子列表的“總字數”計數:wordList = readFile.read().split(', ')totalWords = 0for word in wordList: if ('e' in word): writeFile.write(word + '\n') totalWords += 1writeFile.write("Total words: " + str(totalWords))readFile.close()writeFile.close()使用Python的三元條件:for word in wordList: writeFile.write(word + '\n') if ('e' in word) else 'false'我想知道是否有一種方法可以執行寫入操作并在單個三元條件中遞增totalWords。我還想知道,除了使用“false”或None之外,是否有更合適的方法來處理其他條件,因為我們只是跳過一個不符合條件的單詞?提前致謝。
1 回答

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
您不能真正執行寫入操作并使用單個三元語句(一個襯里)遞增 totalWords。您已經正確實現了代碼,無需修改代碼。
如果要增強代碼,可以使用復合語句,如下所示,with
with open('read_filename', 'r') as readFile, open('write_filename', 'w') as writeFile:
wordList = readFile.read().split(', ')
totalWords = 0
for word in wordList:
if ('e' in word):
writeFile.write(word + '\n')
totalWords += 1
writeFile.write("Total words: " + str(totalWords))
添加回答
舉報
0/150
提交
取消