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

发布于 2024-09-10 19:28:26 字数 288 浏览 6 评论 0原文

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

我有:

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

并且我想要:

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

我对此的解决方案是:

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

是否有更Pythonic的方法来做到这一点?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

老旧海报 2024-09-17 19:28:26

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

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

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

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

入画浅相思 2024-09-17 19:28:26

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

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

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

myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
你在看孤独的风景 2024-09-17 19:28:26

怎么样:

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

How about:

>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
撩动你心 2024-09-17 19:28:26

我认为最Pythonic的解决方案是

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

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

result = ', '.join(tuple_strings)

I think the most Pythonic solution is

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

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

result = ', '.join(tuple_strings)
只有影子陪我不离不弃 2024-09-17 19:28:26

怎么样

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

How about

l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)
故人爱我别走 2024-09-17 19:28:26

我认为这非常巧妙:

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

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

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.

醉生梦死 2024-09-17 19:28:26

还有三个:)

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)'

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)'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文