Python - convert list of tuples to string
将元组列表转换为字符串最简单的方法是什么?
我有:
1  | [(1,2), (3,4)]  | 
我想要:
1  | "(1,2), (3,4)"  | 
号
我的解决方案是:
1 2 3 4 5  | l=[(1,2),(3,4)] s="" for t in l: s +="(%s,%s)," % t s = s[:-1]  | 
有没有比这更像Python的方法?
您可以尝试类似的操作(另请参见ideone.com上的):
1 2 3  | myList = [(1,2),(3,4)] print",".join("(%s,%s)" % tup for tup in myList) # (1,2),(3,4)  | 
您可能需要使用一些简单的方法,例如:
1 2 3  | >>> l = [(1,2), (3,4)] >>> str(l).strip('[]') '(1, 2), (3, 4)'  | 
号
…这很方便,但不能保证正确工作
怎么样:
1 2 3  | >>> tups = [(1, 2), (3, 4)] >>> ', '.join(map(str, tups)) '(1, 2), (3, 4)'  | 
。
最常见的方法是
1 2 3 4 5  | tuples = [(1, 2), (3, 4)] tuple_strings = ['(%s, %s)' % tuple for tuple in tuples] result = ', '.join(tuple_strings)  | 
。
我觉得这很干净:
1 2 3  | >>> l = [(1,2), (3,4)] >>>"".join(str(l)).strip('[]') '(1,2), (3,4)'  | 
。
试试看,这对我来说很有魅力。
怎么样
1 2 3  | l = [(1, 2), (3, 4)] print repr(l)[1:-1] # (1, 2), (3, 4)  | 
还有三个:)
1 2 3 4 5 6 7 8 9 10  | 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)'  |