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)
..这很方便,但不能保证正常工作
pil*_*her 17
怎么样:
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
Run Code Online (Sandbox Code Playgroud)