gpt4 book ai didi

python - 使用 numpy delete 和 enumerate 时索引错误

转载 作者:行者123 更新时间:2023-12-01 23:06:36 24 4
gpt4 key购买 nike

python 3.9

我有一个 numpy ndarray 的字符串。实际数组有数千个字符串,但假设:

words_master = ['CARES' 'BARES' 'CANES' 'TARES' 'PARES' 'BANES' 'BALES' 'CORES' 'BORES'
'MARES']

我正在尝试创建一个函数,该函数返回一个列表,其中包含给定字符的字符串已被删除。这用作 while 循环和 if 语句:

                index = 0
temp = []
while index != len(words_master):
idx = words_master[index]
if 'A' in idx:
temp.append(index)
index += 1
words_master = np.delete(words_master, temp)

因为这仍然是一个 for 循环和 if 语句,我想知道是否可以使用列表理解来提高效率。

对此我最好的猜测是:

words_master = np.delete(words_master, np.argwhere([x for x, item in enumerate(words_master) if 'A' in item]))

这里的逻辑是 np.delete 将获取初始数组,然后删除 np.argwhere 设置的索引处的所有项目。然而,它给出了这个输出:

['CARES' 'BORES' 'MARES']

它似乎忽略了第一个和最后一个元素?

其他奇怪之处:如果我在项目中使用“CARES”,它会返回列表而不做任何更改:

['CARES' 'BARES' 'CANES' 'TARES' 'PARES' 'BANES' 'BALES' 'CORES' 'BORES'
'MARES']

如果我使用任何其他参数(“MARES”或“M”或“O”),它似乎会返回没有第一个词的完整列表:

['BARES' 'CANES' 'TARES' 'PARES' 'BANES' 'BALES' 'CORES' 'BORES' 'MARES']

我试过:

  • 使用索引,例如使用 (reversed(list(enumerate.. 或使索引列表为 -1。但是,这些会导致相同类型的模式,但只是移位了。
  • 改用 np.where(),但遇到了类似的问题。

我想知道是否有一种干净的方法来解决这个问题?还是 while 循环/if 语句是最好的选择?

编辑:对于“为什么不使用列表”这个问题,我读到 numpy 数组比 python 列表快很多,当我测试这个相同的 for 循环时,除了使用带有 remove() 函数的 python 列表,它在更大的数据集上慢 10 倍。

最佳答案

import numpy as np

words_master = np.array(['CARES', 'BARES', 'CANES', 'TARES', 'PARES', 'BANES', 'BALES', 'CORES', 'BORES', 'MARES']

是的。这可以更清楚地写成 bool 索引的列表推导。

bad_char = "A"
words_without_char = words_master[[bad_char not in x for x in words_master]]

>>> words_without_char
array(['CORES', 'BORES'], dtype='<U5')

也可以直接列一个列表:

>>> [x for x in words_master if bad_char not in x]
['CORES', 'BORES']

关于python - 使用 numpy delete 和 enumerate 时索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70760190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com