为了提高效率,我正在尝试将此代码转换为使用列表理解。由于程序有一个while
循环,如果可能的话,解决方案可能会使用takewhile
函数。在
此程序将文本分成160个字符块,确保来自同一个单词的字母保持在一起:
txt = ("It was the best of times, it was the worst of times, it was " +
"the age of wisdom, it was the age of foolishness, it was the " +
"epoch of belief, it was the epoch of incredulity, it was the " +
"season of Light, it was the season of Darkness, it was the " +
"spring of hope, it was the winter of despair, we had " +
"everything before us, we had nothing before us, we were all " +
"going direct to Heaven, we were all going direct the other " +
"way-- in short, the period was so far like the present period," +
" that some of its noisiest authorities insisted on its being " +
"received, for good or for evil, in the superlative degree of " +
"comparison only.")
words = txt.split(" ")
list = []
for i in range(0, len(words)):
str = []
while i < len(words) and len(str) + len(words[i]) <= 160:
str.append(words[i] + " ")
i += 1
list.append(''.join(str))
print list
到目前为止,我尝试使用一个包含takewhile
函数的列表理解(我知道它还不起作用):
不建议在一个理解中维护状态,而是使用^{} 函数,它正是您在这里要做的,像这样
相关问题 更多 >
编程相关推荐