【问题标题】:How to divide list according to index position?如何根据索引位置划分列表?
【发布时间】:2021-04-17 12:29:50
【问题描述】:

我有一个latlonalt 的组合列表,按如下所示的顺序排列,现在我想将列表分为三部分,第一部分为lat,第二部分为lon,第三部分为alt

coords = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]

#list format = [lat,lon,alt,lat,lon,alt.....]

例外输出:

lat = [48.92504247289378,48.92504291087322,48.9250463088055....]
lon = [9.147973368734435,9.147998449546572, 9.148013780873235...]
alt = [29707,29707,29707,...]

我试过了:

Split a python list into other "sublists" i.e smaller lists

Python: Split a list into sub-lists based on index ranges

Split a list into parts based on a set of indexes in Python

还有其他一些解决方案,但都没有奏效。

谁能帮我得到预期的输出?

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    怎么样:

    l = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]
    res = [[*l[i::3]] for i in range(3)]
    

    输出是:

    >>> res[0]
    [48.92504247289378, 48.92504291087322, 48.9250463088055, 48.92505484289239, 48.925070689333246]
    >>> res[1]
    [9.147973368734435, 9.147998449546572, 9.148013780873235, 9.148021595289876, 9.148024125370592]
    >>> res[2]
    [29707, 29707, 29707, 29707, 29707]
    

    使用numpy 的另一种可能的解决方案是:

    import numpy as np
    l_np = np.array(l)
    n = 3
    res = l_np.reshape(int(l_np.shape[0]/n), n).T
    
    print(res)
    
    array([[4.89250425e+01, 4.89250429e+01, 4.89250463e+01, 4.89250548e+01,
            4.89250707e+01],
           [9.14797337e+00, 9.14799845e+00, 9.14801378e+00, 9.14802160e+00,
            9.14802413e+00],
           [2.97070000e+04, 2.97070000e+04, 2.97070000e+04, 2.97070000e+04,
            2.97070000e+04]])
    

    res 矩阵中的每一行都是所需的结果。

    【讨论】:

      【解决方案2】:

      只需对列表进行切片即可:

      coords = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]
      lat = coords[::3]
      lon = coords[1::3]
      alt = coords[2::3]
      

      【讨论】:

        【解决方案3】:
        lat = []
        lon = []
        alt = []
        
        for i in range(len(coords)):
           if i % 3 == 0:
              lat.append(coords[i])
           elif i % 3 == 1:
              lon.append(coords[i])
           else:
              alt.append(coords[i])
        

        【讨论】:

          猜你喜欢
          • 2023-02-23
          • 2019-12-10
          • 2011-08-01
          • 1970-01-01
          • 2020-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多