这些单子有什么区别

2024-03-29 09:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我用同样的方法获得了两个列表,只有第一个直接从列表中读取,第二个从postgresql中卸载:

列表1

>>> print(type(list1))
... <class 'list'>
>>> print(list1)
... [array([-0.11152368,  0.1186936 ,  0.00150046, -0.0174517 , -0.14383622,
            0.04046987, -0.07069934, -0.09602138,  0.18125986, -0.14305925])]
>>> print(type(list1[0][0]))
... <class 'numpy.float64'>

列表2

>>> print(type(list2))
... <class 'tuple'>
>>> print(list2)
... (['-0.03803351', '0.07370875', '0.03514577', '-0.07568369', '-0.07438357'])
>>> list2 = list(list2)
>>> print(type(list2))
... <class 'list'>
>>> print(list2)
... [['-0.03803351', '0.07370875', '0.03514577', '-0.07568369', '-0.07438357']]
>>> print(type(list2[0][0]))
... <class 'str'>

我如何看待元素之间的差异?如何从列表2中获取<class 'numpy.float64'>之类的项目?你知道吗

如果类型list1是numpy,为什么它是类“list”?你知道吗


Tags: 方法numpy元素列表postgresqltypearraylist
2条回答

list1是包含一个元素的list,该元素是包含多个floats64numpy.array。你知道吗

list2是包含1个元素的list,该元素是包含多个元素的liststrings(看起来很像floats)。你知道吗

您可以这样转换它们:

import numpy as np

# list of list of strings that look like floats
list2 = [['-0.03803351', '0.07370875', '0.03514577', '-0.07568369', '-0.07438357']]

# list of np.arrays that contain float64's
data = list([np.array(list(map(np.float64, list2[0])))])  # python 3.x

print(data)
print(type(data))
print(type(data[0]))
print(type(data[0][0]))

输出:

[array([-0.03803351,  0.07370875,  0.03514577, -0.07568369, -0.07438357])]
<type 'list'>
<type 'numpy.ndarray'>
<type 'numpy.float64'>

正如Patrick Artner所写。如果list2包含多个数组,则可以使用:

   def string_list_to_int_list(l):
       return l.astype(float)

   converted_list = list(map(string_list_to_int_list, list2))

相关问题 更多 >