0

If you have a list in python lets say:

list1 = ['(18,430)', '(19,430)', '(19,429)', '(19,428)', '(19,427)', '(18,426)',
         '(17,426)', '(17,425)', '(17,424)', '(17,423)', '(17,422)', '(17,421)',
         '(17,420)', '(17,421)']

and you want to convert each element of the list without string and create a new list lets say:

new_list = [(18,430), (19,430), (19,429), (19,428), (19,427), (18,426),
            (17,426), (17,425), (17,424), (17,423), (17,422), (17,421),
            (17,420), (17,421)]

How would you do this in python? Also would each of the individual values in new_list, for example (18,430), be considered a tuple?

Timus
  • 10,974
  • 5
  • 14
  • 28
  • 1
    I recommend trying out the answer first, then posting the code and then asking for help. I looked at 2 of your questions. Both of them do not have your attempts to solve. As you continue using Stack Overflow, please plan to provide your code along with the questions. – Joe Ferndz Dec 29 '20 at 09:14

3 Answers3

1

One easy way to do that for your example would be to use the builtin eval function:

new_list = [eval(item) for item in list1]

If the strings are more complex it would be better to use literal_eval from the ast module:

from ast import literal_eval

new_list = [literal_eval(item) for item in list1]

And yes, each element of new_list would be a tuple.

Timus
  • 10,974
  • 5
  • 14
  • 28
0

First of all, str to tuple conversion will only generate a new tuple with all string chars on it, so you can't make the explicit conversion, either you will need to create a function to convert from a string to a tuple, or slice the parentheses from it, convert it into a number and then create a tuple with that number, later you create a new list and insert the newly created tuples.

0

I just dealt with this a few hours ago. Here's how to do this.

Assumption: All items in list1 are tuples of integers stored as strings.

list1 = ['(18,430)', '(19,430)', '(19,429)',
         '(19,428)', '(19,427)', '(18,426)',
         '(17,426)', '(17,425)', '(17,424)',
         '(17,423)', '(17,422)', '(17,421)',
         '(17,420)', '(17,421)' ]

list2 = [tuple(map(int,(i.replace(')','').replace('(','')).split(','))) for i in list1]
print (list2)

The output of this will be:

[(18, 430), (19, 430), (19, 429), 
 (19, 428), (19, 427), (18, 426), 
 (17, 426), (17, 425), (17, 424), 
 (17, 423), (17, 422), (17, 421), 
 (17, 420), (17, 421)]
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33