Converting lists of tuples to strings Python

梦想与她 提交于 2019-12-22 03:30:16

问题


I've written a function in python that returns a list, for example

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

But i want the output as a string so i can replace the comma with another char so the output would be

'1@1' '2@2' '3@3' 

Any easy way around this?:) Thanks for any tips in advance


回答1:


This looks like a list of tuples, where each tuple has two elements.

' '.join(['%d@%d' % (t[0],t[1]) for t in l])

Which can of course be simplified to:

' '.join(['%d@%d' % t for t in l])

Or even:

' '.join(map(lambda t: '%d@%d' % t, l))

Where l is your original list. This generates 'number@number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').

The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.




回答2:


You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.

ll = [(1,1), (2,2), (3,3)]
['%d@%d' % aa for aa in ll]

This would return a list of strings like:

['1@1', '2@2', '3@3']

You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.




回答3:


' '.join([str(a)+"@"+str(b) for (a,b) in [(1,1),(2,2),(3,3)]])

or for arbitrary tuples in the list,

' '.join(['@'.join([str(v) for v in k]) for k in [(1,1),(2,2),(3,3)]])




回答4:


In [1]: ' '.join('%d@%d' % (el[0], el[1]) for el in [(1,1),(2,2),(3,3)])
Out[1]: '1@1 2@2 3@3'



回答5:


[ str(e[0]) + ',' + str(e[1]) for e in [(1,1), (2,2), (3,3)] ]

This is if you want them in a collection of string, I didn't understand it if you want a single output string or a collection.




回答6:


[str(item).replace(',','@') for item in [(1,1),(2,2),(3,3)]]



回答7:


You only need join and str in a generator comprehension.

>>> ['@'.join(str(i) for i in t) for t in l]
['1@1', '2@2', '3@3']

>>> ' '.join('@'.join(str(i) for i in t) for t in l)
'1@1 2@2 3@3'



回答8:


you could use the repr function and then just replace bits of the string:

>>> original = [(1,1),(2,2),(3,3)]
>>> intermediate = repr(original)
>>> print intermediate
[(1, 1), (2, 2), (3, 3)]
>>> final = intermediate.replace('), (', ' ').replace('[(','').replace(')]','').replace(', ','@')
>>> print final
1@1 2@2 3@3

but this will only work if you know for certain that none of tuples have the following character sequences which need to be preserved in the final result: ), (, [(, )], ,



来源:https://stackoverflow.com/questions/4284648/converting-lists-of-tuples-to-strings-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!