Reputation: 205
I have a list of strings with different numbers of words, eg.
abc = ['apple', 'apple ball', 'cat ', 'ball apple', 'dog cat apple',
'apple ball cat dog', 'cat', 'ball apple']
What I have done is that I have counted the number of spaces in each element. What I want to do now is to print all the elements that have less than 3 spaces in them until I reach an element which has 3 or more spaces and not the elements that come after it... for example in the above list I should get the output
apple
apple ball
cat
dog cat apple
None of the elements after apple ball cat dog
as it has 3 spaces in it. I would also like to point out that I have a list of such lists, so whatever solution you guys can think of, kindly keep in mind that it scales to list of lists :) thank you all...
Upvotes: 3
Views: 1806
Reputation: 94485
>>> sentences = ['apple', 'apple ball', 'cat ', 'ball apple', 'dog cat apple', 'apple ball cat dog', 'cat', 'ball apple']
>>> def return_words_until_N_words(sentences, max_words=3):
... for sentence in sentences:
... words = sentence.split()
... for word in words:
... yield word
... if len(words) >= max_words:
... raise StopIteration
...
>>> print ' '.join(return_words_until_N_words(sentences))
apple apple ball cat ball apple dog cat apple
This returns the words one by one, and works even if multiple spaces separate the words.
If you want the "sentences" one by one, Sven's answer is very good.
It can be adapted to producing words one by one instead:
>>> from itertools import takewhile, chain
>>> for word in chain(*(sentence.split() for sentence in (
takewhile(lambda s: len(s.split()) < 3, sentences)))):
print word
apple
apple
ball
cat
ball
apple
Upvotes: 2
Reputation: 601589
from itertools import takewhile
for s in takewhile(lambda x: x.count(" ") < 3, abc):
print s
For a list of lists, just add another for loop:
for abc in list_of_lists:
for s in takewhile(lambda x: x.count(" ") < 3, abc):
print s
Upvotes: 12