python 创建数组
时间: 2023-10-04 10:12:24 浏览: 32
使用numpy库可以很方便地创建二维数组。可以使用numpy的array函数来创建二维数组,例如:
```python
import numpy as np
# 创建一个2x3的二维数组
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
```
输出结果为:
```
[[1 2 3]
[4 5 6]]
```
其中,`np.array()`函数的参数是一个列表,列表中的每个元素也是一个列表,表示二维数组的每一行。在这个例子中,`[[1, 2, 3], [4, 5, 6]]`表示一个2行3列的二维数组。
相关问题
python 创建数组
以下是几种常用的Python创建数组的方法:
1. 使用numpy库中的array()函数创建数组
```python
import numpy as np
a = np.array([1,2,3,4,5])
print(a) # 输出:[1 2 3 4 5]
```
2. 使用numpy库中的zeros()函数创建全0数组
```python
import numpy as np
b = np.zeros((2,3))
print(b) # 输出:[[0. 0. 0.]
# [0. 0. 0.]]
```
3. 使用numpy库中的arange()函数创建等差数列数组
```python
import numpy as np
c = np.arange(10)
print(c) # 输出:[0 1 2 3 4 5 6 7 8 9]
```
4. 使用numpy库中的linspace()函数创建等差数列数组
```python
import numpy as np
e = np.linspace(1.0,4.0,6)
print(e) # 输出:[1. 1.6 2.2 2.8 3.4 4. ]
```
5. 使用numpy库中的indices()函数创建由坐标构成的数组
```python
import numpy as np
f = np.indices((3,3))
print(f) # 输出:[[[0 0 0]
# [1 1 1]
# [2 2 2]]
#
# [[0 1 2]
# [0 1 2]
# [0 1 2]]]
```
Python创建数组
在Python中,可以使用列表(List)来创建数组。你可以使用方括号([])来表示一个列表,并在其中添加元素。下面是一个例子:
```python
my_list = [1, 2, 3, 4, 5]
```
这将创建一个包含5个整数的列表。你还可以在列表中存储不同类型的元素,例如字符串、浮点数等等。你还可以使用列表的append()方法来在列表末尾添加新元素,例如:
```python
my_list.append(6)
```
这将在列表的末尾添加一个新的元素6。
另外,你也可以使用Python中的数组模块(array module)来创建数组。该模块提供了一个名为array的类,可以用于创建数组。下面是一个例子:
```python
import array
my_array = array.array('i', [1, 2, 3, 4, 5])
```
这将创建一个包含5个整数的数组。在这个例子中,'i'表示数组元素的类型为整数。如果你想要使用浮点数,你可以使用'd'代替'i',例如:
```python
import array
my_array = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
```
这将创建一个包含5个浮点数的数组。
阅读全文
相关推荐















