用第二个空格拆分字符串

Yas*_*mar 3 python string split

输入:

"The boy is running on the train"
Run Code Online (Sandbox Code Playgroud)

预期产量:

["The boy", "boy is", "is running", "running on", "on the", "the train"]
Run Code Online (Sandbox Code Playgroud)

在python中实现这一目标的最简单方法是什么?

Kou*_*sal 9

line="The boy is running on the train"
words=line.split()
k=[words[index]+' '+words[index+1] for index in xrange(len(words)-1)]
print k
Run Code Online (Sandbox Code Playgroud)

产量

['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
Run Code Online (Sandbox Code Playgroud)

  • 我最喜欢这个解决方案,但不是因为性能原因.我认为这是最简单易懂的. (2认同)

Mar*_*ers 8

你拆分所有空格,然后重新加入对:

words = inputstr.split()
secondwords = iter(words)
next(secondwords)

output = [' '.join((first, second)) 
          for first, second in zip(words, secondwords)]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> inputstr = "The boy is running on the train"
>>> words = inputstr.split()
>>> secondwords = iter(words)
>>> next(secondwords)  # output is ignored
'The'
>>> [' '.join((first, second)) for first, second in zip(words, secondwords)]
['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
Run Code Online (Sandbox Code Playgroud)