python生成数组的方法是什么

31次阅读
没有评论

共计 441 个字符,预计需要花费 2 分钟才能阅读完成。

Python 生成数组的方法有多种,以下列举了几种常见的方法:

  1. 使用列表推导式(List Comprehension):
arr = [x for x in range(10)]  # 生成一个包含 0 到 9 的数组 
  1. 使用 range() 函数:
arr = list(range(10))  # 生成一个包含 0 到 9 的数组 
  1. 使用 numpy 库:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])  # 生成一个包含 1 到 5 的 numpy 数组 

arr = np.zeros(5)  # 生成一个包含 5 个 0 的 numpy 数组 

arr = np.ones(5)  # 生成一个包含 5 个 1 的 numpy 数组 

arr = np.arange(10)  # 生成一个包含 0 到 9 的 numpy 数组 
  1. 使用 random 库生成随机数组:
import random

arr = [random.randint(1, 10) for _ in range(5)]  # 生成一个包含 5 个 1 到 10 之间随机整数的数组 

以上是一些生成数组的常见方法,根据具体需求可以选择适合的方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计441字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)