【问题标题】:What is the difference between the lists列表之间有什么区别
【发布时间】:2019-02-12 13:18:08
【问题描述】:

我有两个用同样的方法得到的列表,只有第一个是直接从列表中读取的,第二个是从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'>

如何查看元素的差异?如何从 list2 中获取 &lt;class 'numpy.float64'&gt; 之类的项目?

如果是numpy,为什么类型 list1 是类“列表”?

【问题讨论】:

  • 你的代码告诉你到底有什么区别:第一个是一个包含 numpy float64s 数组的列表,第二个是一个包含字符串列表的元组。
  • 如果它是 numpy,为什么类型 list1 是一个类“列表”? - 你在哪里看到的?
  • type(list1[0]) 是一个 numpy.array。
  • 怎么样?,你有 cotes 那就意味着它是一个字符串

标签: python arrays python-3.x list


【解决方案1】:

list1 是一个包含 1 个元素的 list,它是一个包含多个 floats64numpy.array

list2 是包含 1 个元素的 list,它是包含多个元素的 list strings(恰好看起来很像 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'>

【讨论】:

  • 谢谢,但我没有成功。 print(data) = [array(, dtype=object)],相应地,print(data [0] [0]),表示没有这个索引。
  • @Vasai in python 3 map 返回一个生成器 - 只需将其填充到列表中即可获得我的输出 - 修复代码。
  • 对不起,我根本看不懂numpy模块,我正在尝试写一个循环,我只得到列表中的最后一项,如何添加到列表中而不是替换?
  • @Vasai 为什么要使用 numpy 呢? data 是一个包含 1 个元素的列表,它是一个 ndarray。你可以使用myfloats = data[0].tolist() 来获取一个正常的浮动列表。见docs.scipy.org/doc/numpy/reference/generated/…
【解决方案2】:

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

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

   converted_list = list(map(string_list_to_int_list, list2))

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2015-05-08
    • 2018-12-23
    • 2010-11-07
    • 2014-07-20
    相关资源
    最近更新 更多