Python - 将元组列表转换为字符串

sso*_*ler 17 python tuples list string-formatting

哪个是将元组列表转换为字符串的最pythonic方式?

我有:

[(1,2), (3,4)]
Run Code Online (Sandbox Code Playgroud)

而且我要:

"(1,2), (3,4)"
Run Code Online (Sandbox Code Playgroud)

我的解决方案是:

l=[(1,2),(3,4)]
s=""
for t in l:
    s += "(%s,%s)," % t
s = s[:-1]
Run Code Online (Sandbox Code Playgroud)

是否有更多的pythonic方式来做到这一点?

pol*_*nts 32

您可以尝试这样的事情(另见ideone.com):

myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
Run Code Online (Sandbox Code Playgroud)


myk*_*hal 27

你可能想要使用如下这样简单的东西:

>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
Run Code Online (Sandbox Code Playgroud)

..这很方便,但不能保证正常工作

  • @Rob:`str.strip()`只从末尾删除. (6认同)
  • 依赖列表的内部字符串表示似乎是不好的做法. (6认同)
  • 如果元组是包含[]的字符串元组怎么办? (3认同)

pil*_*her 17

怎么样:

>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
Run Code Online (Sandbox Code Playgroud)