4

我需要从Distance astropy 类中访问浮点值。

这是一个 MWE:

from astropy.coordinates import Distance
from astropy import units as u

d = []
for _ in range(10):
    d.append(Distance(_, unit=u.kpc))

这会产生一个<class 'astropy.coordinates.distances.Distance'>对象列表:

[<Distance 0.0 kpc>, <Distance 1.0 kpc>, <Distance 2.0 kpc>, <Distance 3.0 kpc>, <Distance 4.0 kpc>, <Distance 5.0 kpc>, <Distance 6.0 kpc>, <Distance 7.0 kpc>, <Distance 8.0 kpc>, <Distance 9.0 kpc>]

我需要存储浮点数(而不是对象),但我不知道如何访问它们。由于这个 MWE 是更大代码的一部分,我不能只做d.append(_). 我需要从Distance类生成的对象中访问浮点数。

添加:

我尝试将列表转换为 numpy 数组:

np.asarray(d)

但我得到:

ValueError: setting an array element with a sequence.
4

3 回答 3

4

你想要对象的value属性Distance

d = []
for _ in range(10):
    d.append(Distance(_, unit=u.kpc).value)

...但是你也可以只使用你的变量_而不首先实例化这些对象。或者,也许我误解了什么。

另一种说法:

>>> [i.value for i in d]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
于 2015-11-25T13:57:33.357 回答
3

为了清楚起见,一个Distance对象可以像一个数组。Distance列出所有相同单元的单个对象是愚蠢和浪费的。相反,你可以做

>>> dists = Distance(np.arange(10), unit=u.kpc)  # Note the use of a Numpy array
>>> dists
<Distance [ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.] kpc>

大多数其他代码应该将其识别为 Numpy 数组并采取相应措施。虽然如果没有,你总是可以做

>>> dists.value
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

得到一个ndarray以 kpc 为单位的原始 Numpy。不要使用许多Distance对象的列表。非常浪费!

于 2015-11-26T00:08:05.347 回答
1

你的意思是

d = []
for _ in range(10):
    x = Distance(_, unit=u.kpc)
    d.append(x.kpc)  # x.Mpc , x.lightyear, etc. 

或者

d = []
for _ in range(10):
    d.append( Distance(_, unit=u.kpc).kpc ) # Distance(_, unit=u.kpc).lightyear
于 2015-11-25T14:07:27.707 回答