2012-01-11 150 views
3

我有一個字符串列表,其中包含不同數量的單詞,例如。Python:從列表中打印元素直到特定元素

abc = ['apple', 'apple ball', 'cat ', 'ball apple', 'dog cat apple', 
     'apple ball cat dog', 'cat', 'ball apple'] 

我所做的是我已經計算了每個元素中的空格數。我現在想要做的是打印所有在它們中少於3個空格的元素,直到我到達具有3個或更多空格的元素,而不是後面的元素......例如在上面的列表中,我應該得到輸出

apple 
apple ball 
cat 
dog cat apple 

apple ball cat dog之後沒有元素,因爲它有3個空格。我還想指出,我有這樣的名單列表,所以無論你們可以想到的任何解決方案,請記住,它縮放到列表的名單:)謝謝大家...

回答

12

嘗試itertools.takewhile()

from itertools import takewhile 
for s in takewhile(lambda x: x.count(" ") < 3, abc): 
    print s 

對於列表的列表,只需添加一個for循環:

for abc in list_of_lists: 
    for s in takewhile(lambda x: x.count(" ") < 3, abc): 
     print s 
2
>>> 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 

這將返回字一個一個的,即使多個空格分隔字的作品。

如果你想要一個一個的「句子」,斯文的答案是非常好的。

它可適合於生產詞語逐個代替:

>>> 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