使用 Python 三元条件运算符执行多个操作

这个简单的程序从文本文件中读取单词列表,并将子列表写入另一个文件,子列表的“总字数”计数:


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))

readFile.close()

writeFile.close()

使用Python的三元条件:


for word in wordList:

    writeFile.write(word + '\n') if ('e' in word) else 'false'

我想知道是否有一种方法可以执行写入操作并在单个三元条件中递增totalWords。我还想知道,除了使用“false”或None之外,是否有更合适的方法来处理其他条件,因为我们只是跳过一个不符合条件的单词?提前致谢。


肥皂起泡泡
浏览 115回答 1
1回答

红糖糍粑

您不能真正执行写入操作并使用单个三元语句(一个衬里)递增 totalWords。您已经正确实现了代码,无需修改代码。如果要增强代码,可以使用复合语句,如下所示,withwith 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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python