文字列からタプルのリストを作成したいと思います。基本的に、次のことを考えると、
s = "a b c d"
w = s.split()
以下のタプルのリストが欲しいのですが:
[(a, b), (b, c), (c, d)]
append関数とforループを使用する必要があるように感じますが、行き詰まります。どうすればいいですか?
>>> s = "a b c d"
>>> w = s.split()
>>> zip(w, w[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd')]
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')]
s = "a b c d"
s = s.split(" ")
c=[]
for i in range(len(b)-1):
c.append((b[i],b[i+1]))
list comprehension
s = "a b c d"
s = s.split(" ")
d=[(s[i],s[i+1])for i in range(len(s)-1)]