【问题标题】:Merge two lists to create a list which contains items of the two lists as lists合并两个列表以创建一个列表,其中包含两个列表的项目作为列表
【发布时间】:2021-02-02 09:39:03
【问题描述】:

我想合并两个列表:

lon: [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]

lat: [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]

得到:

coordinates: [[14.21055347, 48.22824817], [14.21055347, 48.22824817], [16.39356558, 48.18617251], [16.39356558, 48.18617251], [14.21055347, 47.65823679]]

如何有效地处理很长的经纬度列表?

感谢您的帮助!

【问题讨论】:

  • 坐标 = list(zip(lon,lat))

标签: python list merge coordinates


【解决方案1】:

您需要为此使用zip() 函数。像大多数 python3 内置函数一样,它使用迭代器,因此非常高效。

>>> lon = [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]
>>> lat = [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]
>>> coordinates = zip(lon, lat)
>>> print(list(coordinates))
[(14.21055347, 48.22824817), (14.21055347, 48.22824817), (16.39356558, 48.18617251), (16.39356558, 48.18617251), (14.21055347, 47.65823679)]

【讨论】:

    【解决方案2】:

    您可以利用map 内置函数以及lambda expressions。

    lon = [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]
    lat = [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]
    
    coordinates = list(map(lambda x, y: [x, y], lon, lat))
    
    print(coordinates)
    >>> [[14.21055347, 48.22824817], [14.21055347, 48.22824817], [16.39356558, 48.18617251], [16.39356558, 48.18617251], [14.21055347, 47.65823679]]
    

    【讨论】:

    • Python 内置的 zip 命令比这更高效。
    • zip 函数返回一个元组迭代器,这不是帖子想要的。
    • 我知道。我只是提到,元组列表是用于此类目的的更好的数据结构,zip 函数是一种有效的方法。你的方法没有问题。
    • 谢谢 - 这正是我需要的!如果可以的话,还有一个问题 - 有没有办法只删除那些连续的重复项? BRG
    • 您可以使用groupby。有关示例,请参阅this answer。
    【解决方案3】:
    lon = [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]
    lat = [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]
    
    coordinates = [[i,j] for i,j in zip(lon, lat)]
    
    print(coordinates)
    

    【讨论】:

    • 您好,欢迎来到 SO!虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读tour和How do I write a good answer?
    【解决方案4】:

    我不太确定我是否正确理解了您的问题,但如果您想匹配这两个数组,请执行以下操作:

    name = [array1, array2]

    【讨论】:

    • OP 想要组合每个元素。
    【解决方案5】:

    只需使用地图功能

    lon = [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]
    lat = [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]
    coordinates = list(map(lambda x,y: [x,y], lon,lat))
    print(coordinates)
    

    输出是:- [[14.21055347, 48.22824817], [14.21055347, 48.22824817], [16.39356558, 48.18617251], [16.39356558, 48.18617251], [14.21055347, 47.21055347, 476]]56>

    Map 需要一个函数作为输入,所以不得不引入 lambda 函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 2015-04-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2012-01-06
      相关资源
      最近更新 更多