簡體   English   中英

從字符串中列出元組,

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM