[英]making a list of tuples from a string,,
我想从字符串中列出元组。 基本上,鉴于以下情况,
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.