You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取列表中每个numpy数组的首个元素?

问题

我编写了如下Python代码:

import numpy as np


a=0.142
c1=np.array([0,0])
c2=np.array([a,0]) #[nm]
a1= np.array([3/2*a,3**0.5/2*a])
a2= np.array([3/2*a,-3**0.5/2*a])

my_list = [] 
def Rnm_1():
    for n in range(10):
        for m in range(10):
            Rnm_1= c1 + (n*a1+m*a2)
            my_list.append(Rnm_1)
    return my_list

调用Rnm_1()后会得到包含多个numpy数组的列表,我希望:

  1. 访问每个数组的首个元素(即x坐标)
  2. 使用所有数组中的x、y值计算距离

解决方案

1. 访问每个数组的首个元素

有两种常用实现方式:

方式一:循环遍历列表

直接遍历列表中的每个numpy数组,通过索引[0]提取首个元素:

points = Rnm_1()
# 遍历获取每个点的x坐标
for point in points:
    x = point[0]
    # 这里可以对x做打印、存储等操作

方式二:转为numpy数组批量提取(更高效)

把列表转换为二维numpy数组,通过切片一次性提取所有x坐标:

points = Rnm_1()
points_array = np.array(points)  # 形状为(100,2),100个点,每个点含2个坐标值
all_x = points_array[:, 0]  # 提取所有行的第0列,即所有点的x坐标

2. 计算距离

计算每个点到原点的距离

利用numpy的广播特性,批量计算所有点到原点的距离:

# 方法一:手动计算平方和开根号
distances_to_origin = np.sqrt(points_array[:,0]**2 + points_array[:,1]**2)

# 方法二:用numpy内置的范数函数更简洁
distances_to_origin = np.linalg.norm(points_array, axis=1)

计算所有点之间的两两距离

可以用scipy的工具快速实现:

from scipy.spatial.distance import cdist
pairwise_distances = cdist(points_array, points_array)
# pairwise_distances[i][j]表示第i个点到第j个点的距离

如果不想依赖scipy,也可以用numpy手动实现:

# 扩展维度后计算坐标差的平方和,再开根号
diff = points_array[:, np.newaxis] - points_array[np.newaxis, :]
pairwise_distances = np.sqrt(np.sum(diff**2, axis=2))

内容的提问来源于stack exchange,提问作者nouha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:10:26