2rs*_*2ts 5 python list-comprehension
说,我们需要一个程序来的字符串列表和分裂他们,并追加的前两个单词,在一个元组,到列表,并返回该列表; 换句话说,一个程序,它给你每个字符串的前两个单词.
input: ["hello world how are you", "foo bar baz"]
output: [("hello", "world"), ("foo", "bar")]
Run Code Online (Sandbox Code Playgroud)
它可以这样写(我们假设有效输入):
def firstTwoWords(strings):
result = []
for s in strings:
splt = s.split()
result.append((splt[0], splt[1]))
return result
Run Code Online (Sandbox Code Playgroud)
但列表理解会更好.
def firstTwoWords(strings):
return [(s.split()[0], s.split()[1]) for s in strings]
Run Code Online (Sandbox Code Playgroud)
但这涉及到两个电话split().有没有办法在理解中只执行一次拆分?我尝试了自然而然的,它是无效的语法:
>>> [(splt[0],splt[1]) for s in strings with s.split() as splt]
File "<stdin>", line 1
[(splt[0],splt[1]) for s in strings with s.split() as splt]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
那么,在这种特殊情况下:
def firstTwoWords(strings):
return [s.split()[:2] for s in strings]
Run Code Online (Sandbox Code Playgroud)
但是,否则,您可以使用一个生成器表达式:
def firstTwoWords(strings):
return [(s[0], s[1]) for s in (s.split() for s in strings)]
Run Code Online (Sandbox Code Playgroud)
如果性能实际上很重要,那就使用一个函数.