将一长串坐标转换成列表

Convert a long string of coordinates into a list

我有一长串用逗号分隔的坐标。

['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']

将此字符串转换为如下所示的坐标列表的最简单方法是什么?

[(22.98795, 74.5936), (55.26964, 124.43686), (39.34479, 124.53541)]

我希望有比这更简单的解决方案

coords = "['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']"
x = coords.split("', '")
x[0] = x[0][2:]
x[-1] = x[-1][:-2]
>>> from ast import literal_eval
>>> coords = "['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']"
>>> l = literal_eval(coords)
>>> l
['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']
>>> [tuple(map(float, i.split(','))) for i in l]
[(22.98795, 74.5936), (55.26964, 124.43686), (39.34479, 124.53541)]

作为 one-liner:

coords = [tuple(map(float, i.split(','))) for i in literal_eval(coords)]

或者,由于 22.98795, 74.5936 恰好是元组的有效文字,因此再次使用 literal_eval

coords = list(map(literal_eval, literal_eval(coords)))

您可以使用 str.strip 方法改进原始方法,即:

coords = "['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']"
x = coords.strip("[']").split("', '")
print(x)

输出:

['22.98795, 74.5936', '55.26964, 124.43686', '39.34479, 124.53541']

strip 删除它在参数中获得的前导和尾随字符。请记住 xstrlist,如果您需要 tuplefloat,则需要进一步处理。