Python 截断切片赋值

标签 python arrays list numpy

我想知道为什么每当我将 float 分配给 numpy 数组时 Python 都会将数字截断为整数:

import numpy as np

lst = np.asarray(list(range(10)))

print ("lst before assignment: ", lst)
lst[:4] = [0.3, 0.5, 10.6, 0.2];
print ("lst after assignment: ", lst)

输出:

lst before assignment:  [0 1 2 3 4 5 6 7 8 9]
lst after assignment:  [ 0  0 10  0  4  5  6  7  8  9]

为什么要这样做?由于您不需要在语言中指定类型,我无法理解为什么 numpy 会在分配给数组(包含整数)之前将 float 转换为 int

最佳答案

与 python 的原生列表相反,numpy 数组是有类型的。尽管这在像 python 这样的动态类型语言中可能违反直觉,但它源于这样一个事实,即 numpy 基本上是一个围绕高度优化的 ` 代码的 python 包装器。

您可以通过将 dtype 关键字参数中的所需数据类型传递给 numpy.array 构造函数来更改 numpy 数组的数据类型:

 numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

dtype : data-type, optional

The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.

numpy constructor

dtype values

关于Python 截断切片赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365326/

相关文章:

c - 将结构插入动态数组

java - java I/O 的字符串数组逻辑问题

javascript - 如何根据对象的两个值对填充有对象的数组进行排序?

python - Scrapy 与 TOR (Windows)

python - 使用JQ从CloudFormation.template.json中删除 block

jquery - polymer 核心列表 - 只显示足够的元素来填充视口(viewport)

python:实例化模块中的所有子类及其函数输出

java - 分配列表并保留引用

python - 在Python中调用R包的问题

python - 使用 xml.etree.ElementTree 更改 xml 元素文本