[英]Sort Coordinates in Python
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] [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]它应该是 [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 ";"您的“列表”看起来更像是一个
string
,带有“;” and "," to separate 2D points and their values.和“,”来分隔二维点和它们的值。 I imagine that you want a
list
of tuples, that represent the x and y coordinates?我想你想要一个代表 x 和 y 坐标的元组
list
? So first you need to split your string
into a list
所以首先你需要将你的
string
拆分成一个list
li = li.split(';')
Now you have a list
of string
s, that you need to split into pairs of float
values.现在您有一个
string
list
,您需要将其拆分为成对的float
值。 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.现在您有了一个可以以某种方式排序的坐标
list
。 Maybe smallest x
first or something.也许首先最小的
x
或其他东西。 Use Python's sorted
build-in function to do that, eg使用 Python 的
sorted
内置函数来做到这一点,例如
sorted_li = sorted(li, key=lambda x: x[0])
The docs are here, read them.文档在这里,阅读它们。
https://docs.python.org/3.6/library/functions.html#sorted https://docs.python.org/3.6/library/functions.html#sorted
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.