numpy.atleast_1d
numpy.atleast_1d(*arys) [source]
将输入转换为至少一维的数组。
标量输入被转换为一维数组,而高维输入被保留。
参数 : | arys1, arys2, … :array_like 一个或多个输入数组。 |
返回值 : | ret :ndarray 一个数组或数组列表,每个数组均带有 |
例子
1)标量输入
import numpy as np
a = 5
result = np.atleast_1d(a)
print(result)
# 输出: [5]
2)数组输入
import numpy as np
b = np.array([1, 2, 3])
result = np.atleast_1d(b)
print(result)
# 输出: [1 2 3]
3)多个输入
import numpy as np
c = 4
d = [5, 6]
e = np.array([[7, 8], [9, 10]])
result = np.atleast_1d(c, d, e)
for arr in result:
print(arr)
# 输出:
# [4]
# [5 6]
# [[ 7 8]
# [ 9 10]]
4)处理0维数组
import numpy as np
f = np.array(3)
result = np.atleast_1d(f)
print(result)
# 输出: [3]
5)使用示例
import numpy as np
# 将标量转换为至少一维的数组
result1 = np.atleast_1d(1.0)
print(result1)
# 输出: array([1.])
# 输入是多维数组,输出保持不变
x = np.arange(9.0).reshape(3, 3)
result2 = np.atleast_1d(x)
print(result2)
# 输出:
# array([[0., 1., 2.],
# [3., 4., 5.],
# [6., 7., 8.]])
# 检查输入与输出是否为同一对象
same_object = np.atleast_1d(x) is x
print(same_object)
# 输出: True
# 多个输入,包括标量和列表
result4 = np.atleast_1d(1, [3, 4])
for arr in result4:
print(arr)
# 输出:
# array([1])
# array([3, 4])