gpt4 book ai didi

python - 如果满足条件python从数组中减去一个数字

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:07 26 4
gpt4 key购买 nike

我在 python 中的 if 条件中面临一个非常基本的问题。

current_img_list 数组的维度为 (500L,1)。如果这个数组中有数字 82459,我想将它减 1。

index = np.random.randint(0,num_train-1,500)
# shape of current_img_list is (500L,1)
# values in index array is randomized
current_img_list = train_data['img_list'][index]
# shape of current_img_list is (500L,1)

if (any(current_img_list) == 82459):
i = np.where(current_img_list == 82459)
final_list = i-1

变量说明——train_data是dict类型。它有 4 个元素。 img_list 是大小为 (215375L,1) 的元素之一。 num_train 的值为 215375,index 的大小为 (500L,1)

首先我不知道这个循环是否有效。我尝试了 all() 函数和 numpy.where() 函数但没有成功。其次,我想不出一种方法来直接从存储它的索引中从 82459 中减去 1,而不影响此数组中的其余值。

谢谢

最佳答案

在 Python 中遍历数组比让 numpy 的向量化运算符执行它们的操作要慢得多:

import numpy as np

num_train = 90000 # for example
index = np.random.randint(0,num_train-1,500)
index[index == 82459] -= 1

关于python - 如果满足条件python从数组中减去一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44810755/

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