python:优雅和代码保存方式转换列表

时间:2013-01-08 21:09:15

标签: python performance optimization coding-style

首先抱歉这个简单的问题。我有一个列表(只是一个例子)

points = [[663963.7405329756, 6178165.692240637],
 [664101.4213951868, 6177971.251818423],
 [664099.7474887948, 6177963.323432223],
 [664041.432877932, 6177903.295650704],
 [664031.8017317944, 6177895.797176996],
 [663963.7405329756, 6178165.692240637]]

我需要将其转换为以下形式

points = [(663963.7405329756, 6178165.692240637),
 (664101.4213951868, 6177971.251818423),
 (664099.7474887948, 6177963.323432223),
 (664041.432877932, 6177903.295650704),
 (664031.8017317944, 6177895.797176996),
 (663963.7405329756, 6178165.692240637)]

使用shapely module创建Polygon对象。我写了几个循环,但真的不优雅和耗时。您知道将第一个列表转换为第二个列表的最佳方法吗?

由于

4 个答案:

答案 0 :(得分:5)

converted = map(tuple, points) # Python 2
converted = list(map(tuple, points)) # or BlackBear's answer for Python 3
converted = [tuple(x) for x in points] # another variation of the same

答案 1 :(得分:2)

converted = [(a,b) for a,b in points]

答案 2 :(得分:2)

converted = [tuple(l) for l in points]

与@BlackBear给出的解决方案相比,这适用于任意大小的子列表。

答案 3 :(得分:1)

points = [tuple(x) for x in points]