2012-01-11 24 views
3

私は、単語の数が異なる文字列のリストを持っています。Python:リストから要素を特定の要素まで印刷する

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

私が行ったことは、各要素のスペース数を数えたことです。ここでやりたいことは、3つ以上の空白を持つ要素に、3つ以上の空白があり、後に続く要素には到達しなくなるまで、3つ以下の空白を持つすべての要素を印刷することです。 apple ball cat dog後の要素の

apple 
apple ball 
cat 
dog cat apple 

なし、それはそれで3つのスペースを持っているような出力を得ることはありません。私はそのリストのリストを持っていることを指摘したいと思います。皆さんが考えている解決策があれば、それはリストのリストに比例していることを心に留めておいてください:)

答えて

12

Try itertools.takewhile()

リストのリストについては
from itertools import takewhile 
for s in takewhile(lambda x: x.count(" ") < 3, abc): 
    print s 

、ちょうどループのために別のものを追加します。

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 

これは、言葉一つ一つを返し、複数のスペースは、単語を区切る場合でも動作します。

「文章」を1つずつ欲しければ、Svenの答えはとても良いです。

それは言葉の代わりに一つ 1を製造することに適合させることができる。

>>> 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 
関連する問題