【问题标题】:python: elegant and code saving way to convert a listpython:转换列表的优雅和节省代码的方式
【发布时间】:2013-01-08 21:09:14
【问题描述】:

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

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 对象。我写了几个循环,但真的不优雅且耗时。您知道将第一个列表转换为第二个列表的最佳方法吗?

谢谢

【问题讨论】:

    标签: python performance optimization coding-style


    【解决方案1】:
    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
    

    【讨论】:

    • 我认为使用map() 的版本是最有效的版本。并且最短。
    • @PeterStahl 可能。它也适用于 Python 3,但 converted 不会是列表,而是生成器。有时候没关系,这种情况下我也推荐使用map
    【解决方案2】:
    converted = [(a,b) for a,b in points]
    

    【讨论】:

      【解决方案3】:
      converted = [tuple(l) for l in points]
      

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

      【讨论】:

        【解决方案4】:
        points = [tuple(x) for x in points]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-04
          • 2016-05-11
          • 2013-06-03
          • 2015-03-22
          • 1970-01-01
          • 1970-01-01
          • 2016-07-12
          相关资源
          最近更新 更多