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

Python convert for/while into list comprehensions using takewhile

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

words = txt.split(" ")
list = [ [str.append(w+" ") for w in itertools.takewhile( \
        lambda i: i<len(words) and len(str)+len(words[i])<=160,
        words )] for j in range(0, len(words)]
print list

不建议在推导式中维护状态,而是使用 textwrap.wrap 函数,它完全符合您在此处尝试执行的操作,如下所示

>>> 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.']
>>>