我有一个坐标数组如下:
[array([[ 72.57218373, 247.1759997 ]]), array([[ 262.51505688, 158.68137977]]), array([[ 244.53157113, 100.05665591]]), array([[ 245.30108919, 88.97536043]]), array([[ 43.60839312, 82.11394031]]), array([[ 260.62555476, 161.252084 ]]), array([[ 234.46830867, 269.07508699]]), array([[ 284.51718016, 142.55126301]]), array([[ 195.30252058, 84.7559498 ]]), array([[ 141.08621668, 276.6625877 ]]), array([[ 294.18468717, 131.91470926]]), array([[ 35.46840935, 51.14890688]]), array([[ 36.15758189, 131.19703618]]), array([[ 175.95018737, 216.52553084]]), array([[ 62.99149427, 217.7800738 ]]), array([[ 245.81708339, 10.06949286]]), array([[ 137.31450413, 145.10778886]]), array([[ 197.76975618, 75.96150192]]), array([[ 17.87096457, 120.88350573]]), array([[ 262.89229921, 287.40287273]]), array([[ 177.51716203, 101.5694418 ]]), array([[ 97.76530613, 190.06919232]]), array([[ 229.31904186, 97.92874288]])]
我想将此转换为点数,以便我的最终列表应为
形式[(72.57218373, 247.1759997), (262.51505688, 158.68137977), ( 244.53157113, 100.05665591), (245.30108919, 88.97536043), (43.60839312, 82.11394031), (260.62555476, 161.252084), ...]
有人可以帮我解决这个问题吗?
谢谢,
答案 0 :(得分:3)
使用:
new_list = [tuple(arr[0]) for arr in old_list]
因为列表中的每个元素都是一行的二维数组。
注意,您的tuple
对象现在将包含标量numpy对象,可能是numpy.float64
。这可能不太理想,在这种情况下,您可以这样做:
new_list = [tuple(map(float, arr[0])) for arr in old_list]
答案 1 :(得分:2)
以Paul Panzer的建议为基础,
In [38]: list_of_arrs = [array([[ 72.57218373, 247.1759997 ]]), array([[ 262.51505688, 158.68137977]]),..... ]
In [39]: flat_list = np.ravel(list_of_arrs).tolist()
In [40]: list_of_tuples = list(zip(flat_list[0::2], flat_list[1::2]))
In [41]: list_of_tuples
Out[41]:
[(72.57218373, 247.1759997),(262.51505688, 158.68137977),....]
再次根据Paul Panzer的建议,为了提高效率,我们可以避免在构建list_of-tuples
时制作切片的明确副本:
In [22]: list_of_tuples = list(zip(*2*(iter(flat_list),)))
In [23]: list_of_tuples
Out[23]: [(72.57218373, 247.1759997), (262.51505688, 158.68137977), ...]
# explicit copy
In [36]: %%timeit
...: flat_list = 10000*(np.ravel(list_of_arrs).tolist())
...: list_of_tuples = list(zip(flat_list[0::2], flat_list[1::2]))
...:
17 ms ± 345 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# avoiding explicit copy by using an iterator
In [37]: %%timeit
...: flat_list = 10000*(np.ravel(list_of_arrs).tolist())
...: list_of_tuples = list(zip(*2*(iter(flat_list),)))
...:
14.5 ms ± 267 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)