Python:从列表中打印直到特定元素的元素

3 投票
2 回答
1800 浏览
提问于 2025-04-17 10:00

我有一个字符串列表,这些字符串里的单词数量各不相同,比如:

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个空格。我还想提一下,我有这样列表的列表,所以无论你们想到什么解决方案,请记得它要适用于列表的列表哦 :) 谢谢大家……

2 个回答

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

撰写回答