使用 Python 三元条件运算符执行多项操作
Performing multiple actions with Python ternary conditional operator
这个简单的程序从一个文本文件中读取一个单词列表,并将一个子列表写入另一个文件,子列表的计数为 "Total words":
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,是否有更合适的方法来处理 else 条件,因为我们只是跳过不满足条件的单词?
提前致谢。
您不能真正执行写操作并使用单个三元语句(一个衬里)递增 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))
这个简单的程序从一个文本文件中读取一个单词列表,并将一个子列表写入另一个文件,子列表的计数为 "Total words":
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,是否有更合适的方法来处理 else 条件,因为我们只是跳过不满足条件的单词? 提前致谢。
您不能真正执行写操作并使用单个三元语句(一个衬里)递增 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))