Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据索引位置划分列表?_Python_Python 3.x_List - Fatal编程技术网

Python 如何根据索引位置划分列表?

Python 如何根据索引位置划分列表?,python,python-3.x,list,Python,Python 3.x,List,我有一个按如下顺序排列的lat、lon和alt组合列表,现在我想将列表分为三部分:第一部分是lat,第二部分是lon,第三部分是alt coords = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876,

我有一个按如下顺序排列的
lat
lon
alt
组合列表,现在我想将列表分为三部分:第一部分是
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,...]
我试过:

还有一些其他的解决方案,但都不起作用

有人能帮我获得预期的输出吗?

怎么样:

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
矩阵中的每一行都是所需的结果。

仅对列表进行切片即可:

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]
lat=[]
lon=[]
alt=[]
对于范围内的i(len(coords)):
如果i%3==0:
横向附加(坐标[i])
elif i%3==1:
lon.append(coords[i])
其他:
alt.append(坐标[i])