Python使用takewhi将for/while转换为列表理解

2024-04-26 11:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

为了提高效率,我正在尝试将此代码转换为使用列表理解。由于程序有一个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函数的列表理解(我知道它还不起作用):

^{pr2}$

Tags: ofthein程序列表forlenit
1条回答
网友
1楼 · 发布于 2024-04-26 11:16:51

不建议在一个理解中维护状态,而是使用^{}函数,它正是您在这里要做的,像这样

>>> print(textwrap.wrap(txt, 160))
['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.']
>>> 

相关问题 更多 >