|
and use it like that:- >>> first_chars = list(word[0] for word in text.split() if stopif(word == "and"))
- >>> first_chars
- ['I', 'c', 't', 't', 'd', 'b', 'W', 'b']
复制代码 Both version are a bit lacking in elegance and may be surprising to an unsuspecting reader, but I personally find the if <expr> else stop() intuitive enough to actually use.
Just for completeness: You might use itertools.takewhile() to achieve the same effect.- >>> first_chars = [word[0] for word in itertools.takewhile(lambda word: word != "and", text.split())]
- >>> first_chars
- ['I', 'c', 't', 't', 'd', 'b', 'W', 'b']
复制代码 |
|