0

I am trying to convert a list of tuples and strings into a list of tuples as follows:

I have:

[In]: print(lista)
[Out]: [
  ('Enero', "('90.0', '229.0', '0.264', '0.672')"),
  ('Febrero', "('76.0', '262.0', '0.247', '0.821'')"),
  ('Marzo', "('95.0', '133.0', '0.279', '0.390')"),
] 

And I am trying to get:

[In]: print(lista)
[Out]: [
  ('Enero', '90.0', '229.0', '0.264', '0.672'),
  ('Febrero', '76.0', '262.0', '0.247', '0.821'),
  ('Marzo', '95.0', '133.0', '0.279', '0.390'),
] 

Any idea how to remove the ( and )?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Une
  • 3
  • 3
  • 2
    Where does this data come from? I suspect you accidentally stored the string representation of the tuple, rather than the tuple itself. You could fix it now by trying to parse apart the quoted string back into a tuple, but this would be a waste. Ideally, you would just fix the data source so you never end up with that string. – Alexander Mar 30 '21 at 17:17
  • 2
    The first step is to understand what your list actually contains and what you need -- Each element is a `tuple` that contains two strings: `'Enero'`, and `"('90.0', '229.0', '0.264', '0.672')"`. So you don't want to _"remove `"(` and `)"` from your output"_. You actually want to _convert that second string_ (which is a string representation of a tuple) to an actual tuple. Then you want to replace the string representation with the values in this new tuple. – Pranav Hosangadi Mar 30 '21 at 17:20

1 Answers1

0

You can use ast.literal_eval to convert your strings into tuples

lista = [('Enero', "('90.0', '229.0', '0.264', '0.672')"), ('Febrero', "('76.0', '262.0', '0.247', '0.821')"), ('Marzo', "('95.0', '133.0', '0.279', '0.390')")]
lista = [(i,) + literal_eval(j) for i,j in lista]

Output

[('Enero', '90.0', '229.0', '0.264', '0.672'),
 ('Febrero', '76.0', '262.0', '0.247', '0.821'),
 ('Marzo', '95.0', '133.0', '0.279', '0.390')]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218