哪种方法是将元组列表转换为字符串的最pythonic方式?
我有:
[(1,2), (3,4)]
and I want:
"(1,2), (3,4)"
我的解决方案是:
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
有没有更符合Python风格的方法来完成这个任务?
哪种方法是将元组列表转换为字符串的最pythonic方式?
我有:
[(1,2), (3,4)]
and I want:
"(1,2), (3,4)"
我的解决方案是:
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
你可能想要使用像这样简单的东西:
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
...这很方便,但不能保证能正常工作。
str.strip()
只能移除字符串两端的空白字符。 - Ignacio Vazquez-Abrams这样怎么样:
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
怎么样?
l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)
我觉得这很棒:
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
试试吧,对我来说效果非常好。
再来三个 :)
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)'
string.format
方法就可以非常简单地完成工作。如果他们想要其他东西,那么问题应该说明他们想要实现什么。 - S.Lott