简体   繁体   中英

Convert elements of a list in tuples

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

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM