共計 441 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
Python 生成數(shù)組的方法有多種,以下列舉了幾種常見的方法:
- 使用列表推導(dǎo)式(List Comprehension):
arr = [x for x in range(10)] # 生成一個包含 0 到 9 的數(shù)組
- 使用 range() 函數(shù):
arr = list(range(10)) # 生成一個包含 0 到 9 的數(shù)組
- 使用 numpy 庫:
import numpy as np
arr = np.array([1, 2, 3, 4, 5]) # 生成一個包含 1 到 5 的 numpy 數(shù)組
arr = np.zeros(5) # 生成一個包含 5 個 0 的 numpy 數(shù)組
arr = np.ones(5) # 生成一個包含 5 個 1 的 numpy 數(shù)組
arr = np.arange(10) # 生成一個包含 0 到 9 的 numpy 數(shù)組
- 使用 random 庫生成隨機數(shù)組:
import random
arr = [random.randint(1, 10) for _ in range(5)] # 生成一個包含 5 個 1 到 10 之間隨機整數(shù)的數(shù)組
以上是一些生成數(shù)組的常見方法,根據(jù)具體需求可以選擇適合的方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完