Python使用takewhile转换为/ while到列表推导

时间:2015-01-10 05:49:26

标签: python string list-comprehension

我目前正在尝试将此代码转换为使用列表推导以提高效率。由于程序具有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

1 个答案:

答案 0 :(得分:4)

不建议在理解中保持状态,而是使用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.']
>>>