1

How may I convert the square brackets inside a list into parentheses and the parentheses outside the square brackets into square brackets?

Example:

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

What I would ideally like to have is:

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

because as you may notice, the parentheses in the original list encloses two pairs of brackets, but I want it the other way around, for the brackets to enclose two pairs of parentheses.

Stiven G
  • 215
  • 2
  • 7

1 Answers1

1

You are trying to convert innerlist to tuple and outer tuple back to list. You can do this by list comprehension.

In [1]: Lst=[([(1,2)],[(1,2),(1,3)]),([(1,4)],[(1,4),(2,3)])]

In [2]: [list(tuple(k) for k in x) for x in (y for y in Lst)]
Out[2]: [[((1, 2),), ((1, 2), (1, 3))], [((1, 4),), ((1, 4), (2, 3))]]
Praveen
  • 8,945
  • 4
  • 31
  • 49
  • 1
    there is no need of the third loop ie `[[tuple(j)] for i in lst for j in i]` will do – Onyambu Sep 21 '18 at 05:30
  • I just have one more question, since there are some terms with double parentheses which look a little weird, for example ((1,2),). Is it possible to take out a pair, and leave it as (1,2) (with just one parentheses)? Thank you. – Stiven G Sep 21 '18 at 13:00
  • `single-element tuples need a trailing comma, but it's optional for multiple-element tuples` If it is a single element tuple a trailing comma will appear. Other wise it will not treat is as a tuple [this](https://stackoverflow.com/questions/7992559/what-is-the-syntax-rule-for-having-trailing-commas-in-tuple-definitions) may help – Praveen Sep 24 '18 at 04:20