入力:
"The boy is running on the train"
予想される出力:
["The boy", "boy is", "is running", "running on", "on the", "the train"]
Pythonでこれを達成するための最も簡単な解決策は何ですか.
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
出力
['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
すべてのスペースで分割してから、ペアを再結合します。
words = inputstr.split()
secondwords = iter(words)
next(secondwords)
output = [' '.join((first, second))
for first, second in zip(words, secondwords)]
デモ:
>>> 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']
または、次のソリューションitertools.combinations
:
>>> s = "The boy is running on the train"
>>> seen = set()
>>> new = []
>>> for tup in itertools.combinations(s.split(), 2):
... if tup[0] not in seen:
... new.append(' '.join(tup))
... seen.add(tup[0])
...
>>> print new
['The boy', 'boy is', 'is running', 'running on', 'on the', 'the train']
これは実際にはitertools.combinations
:p に使用すべきものではありませんが。