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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3292643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:28:06  来源:igfitidea点击:

Python - convert list of tuples to string

pythonliststring-formattingtuples

提问by ssoler

Which is the most pythonic way to convert a list of tuples to string?

将元组列表转换为字符串的最pythonic 方法是什么?

I have:

我有:

[(1,2), (3,4)]

and I want:

而且我要:

"(1,2), (3,4)"

My solution to this has been:

我对此的解决方案是:

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

Is there a more pythonic way to do this?

有没有更pythonic的方法来做到这一点?

采纳答案by mykhal

you might want to use something such simple as:

你可能想使用一些简单的东西,比如:

>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'

.. which is handy, but not guaranteed to work correctly

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

回答by polygenelubricants

You can try something like this (see also on ideone.com):

您可以尝试这样的操作(另请参见 ideone.com):

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

回答by Benj

How about

怎么样

l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)

回答by pillmuncher

How about:

怎么样:

>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'

回答by blaztinn

Three more :)

还有三个:)

l = [(1,2), (3,4)]

unicode(l)[1:-1]
# u'(1, 2), (3, 4)'

("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'

", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'

回答by luissanchez

I think this is pretty neat:

我认为这很整洁:

>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'

Try it, it worked like a charm for me.

试试吧,它对我来说就像一个魅力。

回答by ValarDohaeris

The most pythonic solution is

最pythonic的解决方案是

tuples = [(1, 2), (3, 4)]

tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]

result = ', '.join(tuple_strings)