-1

I have the following list:

list_c = ['42.2529, -73.7910', '42.079846, -76.499364', '42.361824, -73.597979', '42.035959, -73.580146']

I'd like to convert to this:

list_c2 =  [(42.2529, -73.7910),(42.079846, -76.499364),(42.361824, -73.597979),(42.035959, -73.580146)]

The code am trying is:

list_c2 = [(list_c[i]) for i in range(0, len(list_c))]
print("list_c2 =", list_c)

Unfortunately, the result is exactly the same as list_c

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
lookiluke
  • 71
  • 1
  • 6
  • What do you want to happen if your original list has an odd number of elements? – Patrick Haugh Dec 21 '18 at 21:10
  • i have a slight correction to make to my question: the desired result actually is: list_c2 = [(42.2529, -73.7910),(42.079846, -76.499364),(42.361824, -73.597979),(42.035959, -73.580146)] i.e., just tuples of numbers (without the ' ' marks)! and it doesn't matter how many elements are in the original list, the desired result should always have the same # of elements as the original list. also, i've searched the previous answers, but unfortunately couldn't find any answer to this specific one. the difference i believe is the elements of the original list are already in pairs. – lookiluke Dec 21 '18 at 21:17
  • In that case, your list to floats before running the linked functions: `list_c = [float(x) for x in list_c]` – Patrick Haugh Dec 21 '18 at 21:20
  • that doesn't work. am getting an error ... "Could not convert string to float: '42.2529, -73.7910'. – lookiluke Dec 21 '18 at 21:29

1 Answers1

1

I'm sorry, I misread you list initially. To convert this into pairs of floats, you'll need to split each string on its comma and then make each element a float, then pack them in a tuple:

list_c2 = [tuple(float(item) for item in s.split(',')) for s in list_c]
# [(42.2529, -73.791), (42.079846, -76.499364), (42.361824, -73.597979), (42.035959, -73.580146)]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96