添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Python元组到数组

要将Python元组转换为数组,使用 np.asarray() 函数。numpy asarray()是一个库函数,可以将输入转换为数组。这包括 列表 、图元、图 、图元的图元、列表的图元,以及ndarrays。

如果你以前没有在系统中安装numpy,那么要在系统中 安装numpy ,请输入以下命令:

python3 -m pip install numpy
import numpy as np
tup = (11, 21, 19, 18, 46, 29)
print(tup)
print(type(tup))
print("After converting Python tuple to array")
arr = np.asarray(tup)
print(arr)
print(type(arr))
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
After converting Python tuple to array
[11 21 19 18 46 29]
<class 'numpy.ndarray'>

在这个例子中,我们已经导入了numpy模块。

然后我们使用tuple()函数定义了一个元组。例如,要检查Python中的数据类型,可以使用type()函数。

我们通过使用np.asarray()函数并传递一个元组作为参数,得到了return中的数组。如果我们检查返回值的数据类型,它是一个numpy数组,这正是我们想要的。

将一个列表的元组转换为数组

要将一个列表的元组转换成一个数组,使用np.asarray()函数,然后使用flatten()方法将数组平移,将其转换成一个一维数组:

import numpy as np
tup = ([11, 21, 19], [18, 46, 29])
print("After converting Python tuple of lists to array")
arr = np.asarray(tup)
print(arr)
fla_arr = arr.flatten()
print(fla_arr)
After converting Python tuple of lists to array
[[11 21 19]
 [18 46 29]]
[11 21 19 18 46 29]

numpy.asarray()将一个列表的元组转换为数组。尽管如此,它还是会创建一个二维数组,要想把它转换为一维数组,请使用array.flatten()方法。

使用np.array()方法将元组转换为数组

numpy.array()方法接受一个Python对象作为参数并返回一个数组。我们将传递一个元组对象给np.array()函数,将该元组转换为一个数组:

import numpy as np
tup = ([11, 21, 19], [18, 46, 29])
print("After converting Python tuple to array using np.array()")
arr = np.array(tup)
print(arr)
print("After flattening the array")
fla_arr = arr.flatten()
print(fla_arr)
After converting Python tuple to array using np.array()
[[11 21 19]
 [18 46 29]]
After flattening the array
[11 21 19 18 46 29]

np.array()函数的工作原理与np.asarray()几乎一样,并返回转换后的数组。

假设Python列表是一个数组

如果你不想使用numpy数组而把一个列表作为数组,那么使用列表理解将元组转换为数组:

lt = []
tup1 = (11, 19, 21)
tup2 = (46, 18, 29)
lt.append(tup1)
lt.append(tup2)
arr = [x for xs in lt for x in xs]
print(arr)
[11, 19, 21, 46, 18, 29]

本教程就到此为止。

Python 元组到字典

Python 元组到列表

Python列表到元组

  • 私信
     21,702