Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a list of tuples with a formatting in an efficient manner

I have the following list of tuples

a = [(5, 2), (2, 4)]

And I need to output the following text

(5,2) (2,4)

I have tried

[",".join(str(i) for i in j) for j in a]

And it provides the following list

['5,3', '2,4']

But haven't found an efficient way of getting the desired output, and it must work for a list of tuples of different sizes.

like image 275
A. Yu Avatar asked May 09 '19 23:05

A. Yu


2 Answers

You can use the str.join method with a generator expression like the following:

' '.join('(%s)' % ','.join(map(str, t)) for t in a)

This returns a string with the following content:

(5,2) (2,4)
like image 181
blhsing Avatar answered Oct 25 '22 06:10

blhsing


If all you need to do is get string output then:

  1. Convert to a string
  2. Strip the brackets

str(a).strip("[]")

out: '(5,2) (2,4)'

like image 36
EchoCloud Avatar answered Oct 25 '22 06:10

EchoCloud