I have a list of coordinates like:
[44.64,-123.11;38.91,-121.99;40.35,-122.28;43.21,-123.36;41.77,-122.58;37.77,-122.42]
I need to sort this list. Any suggestions ?
EDIT: Sorry for not sharing the expected output:
It should be [44.64,-123.11;43.21,-123.36;41.77,-122.58;40.35,-122.28;38.91,-121.99;37.77,-122.42]
li = [44.64,-123.11;38.91,-121.99;40.35,-122.28;43.21,-123.36;41.77,-122.58;37.77,-122.42]
Your "list" looks more like a string
, with ";" and "," to separate 2D points and their values. I imagine that you want a list
of tuples, that represent the x and y coordinates? So first you need to split your string
into a list
li = li.split(';')
Now you have a list
of string
s, that you need to split into pairs of float
values. You can do that with two list comprehensions
li = [(float(a.split(',')[0]), float(a.split(',')[1])) for a in li]
Now you have a list
of coordinates that you could sort in some way. Maybe smallest x
first or something. Use Python's sorted
build-in function to do that, eg
sorted_li = sorted(li, key=lambda x: x[0])
The docs are here, read them.
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.