2012-01-11 2 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 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 

이 하나 하나 단어를 반환하고, 여러 공간이 단어를 분리하는 경우에도 작동합니다.

"문장"을 하나씩 원한다면 Sven의 대답은 매우 좋습니다.

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

그것은 단어 대신 하나씩을 생산에 적용 할 수있다