问题描述:

I'm currently trying to convert this code to use list comprehensions in order to improve efficiency. Since the program has a while loop, the solution will likely use the takewhile function, if it's possible.

This program splits text into 160 character chunks, ensuring that letters from the same word stay together:

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

Here is what I have so far, attempting to use a list comprehension containing a use of the takewhile function (I know it won't work yet):

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

网友答案:

Maintaining state inside a comprehension is not recommended, instead use textwrap.wrap function, which does exactly what you are trying to do here, like this

>>> 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.']
>>> 
相关阅读:
Top