Skip to main content
 首页 » 编程设计

python之使用 Numpy bool 数组索引 Python 列表

2025年05月04日10youxin

有没有一种方法可以使用 numpy bool 数组来索引像 x = ['a','b','c'] 这样的 python 列表?我目前收到以下错误:TypeError: only integer arrays with one element can be converted to an index

请您参考如下方法:

通过[]建立索引会 secret 调用对象的__getitem__方法。对于用纯 Python 实现的对象,您可以简单地用适合您需要的任何函数覆盖此方法。然而,列表是用 C 实现的,因此您不能替换 list.__getitem__。因此,没有直接的方法来执行您的请求。

但是,您可以从列表中创建一个 NumPy 数组,然后对其进行 NumPy 风格的 bool 索引:

import numpy as np 
 
x = ['a', 'b', 'c'] 
 
mask = np.array([True, False, True]) 
x_arr = np.asarray(x, dtype=object) 
output = x_arr[mask]  # Get items 
x_arr[mask] = ['new', 'values']  # Set items 

不幸的是,np.asarray 不能简单地查看您的列表,因此列表只是被复制。这意味着当为x_arr的元素赋新值时,原始的x是不变的。

如果您真的想要在列表上使用 NumPy bool 索引的全部功能,您必须从头开始编写一个函数,并且您将无法使用 [] 索引语法。