如何将 Python 元组转换为数组

Python没有像其他编程语言那样内置数组数据类型,但是如果你使用像Numpy这样的库,你会创建一个数组。

要将元组转换为数组:

  1. 使用 numpy.asarray() 方法
  2. 使用 numpy.array() 方法

Python元组到数组

要将 Python 元组转换为数组,请使用 np.asarray() 函数。 numpy asarray() 是将输入转换为数组的库函数。 这包括列表、元组、元组、元组的元组、列表的元组和 ndarray。

如果您以前没有在系统中安装 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)

After converting Python tuple to array
[11 21 19 18 46 29]

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

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

我们通过使用 np.asarray() 函数并传递一个元组作为参数来获得数组作为回报。 如果我们检查返回值的数据类型,它是一个我们想要的 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列表到一个元组

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Krunal所有,未经许可,不得转载
你可能还喜欢