从字符串中制作元组列表,

use*_*726 1 python string tuples list

我想用字符串列出元组列表.基本上,给出以下内容,

s = "a b c d"
w = s.split()
Run Code Online (Sandbox Code Playgroud)

我想要下面的元组列表:

[(a, b), (b, c), (c, d)]
Run Code Online (Sandbox Code Playgroud)

我觉得我应该使用append函数和for循环,但我被卡住了.我该怎么做?

Joh*_*ooy 9

>>> s = "a b c d"
>>> w = s.split()
>>> zip(w, w[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd')]
Run Code Online (Sandbox Code Playgroud)

如果你真的想要使用for循环append,你可以替换zip()这样的

>>> res = []
>>> for i in range(1, len(w)):
...     res.append((w[i-1], w[i]))
... 
>>> res
[('a', 'b'), ('b', 'c'), ('c', 'd')]
Run Code Online (Sandbox Code Playgroud)