web-dev-qa-db-ja.com

Python-タプルのリストを文字列に変換します

タプルのリストを文字列に変換する最もPython的な方法はどれですか?

私が持っています:

[(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]

これを行うためのよりPython的な方法はありますか?

18
ssoler

あなたは次のような単純なものを使いたいかもしれません:

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

..便利ですが、正しく動作することが保証されていません

28
mykhal

次のようなものを試すことができます( ideone.comも参照 ):

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

どうですか:

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

最もPythonicなソリューションは

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

Tuple_strings = ['(%s, %s)' % Tuple for Tuple in tuples]

result = ', '.join(Tuple_strings)
1
ValarDohaeris

これはかなりきちんとしていると思います:

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

試してみて、それは私にとって魅力のように働きました。

1
luissanchez

いかがですか

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

さらに3つ:)

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