random.choice的存储值在调用twi时被替换

2024-05-20 19:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.5。我有三个一维数组,我想从每个数组中随机选择一个值。我首先使用random.choice()选择随机值并将它们存储在一个变量中。但是,当第二次调用random.choice()时,存储在变量中的值将被替换。以下是我的代码片段:

import numpy as np
import random

a_onc = np.array([1,2,3,4,5])
mass_onc = np.array([10,11,12,13,14,15])
age_onc = np.array([23,24,25,21,22,27])

achoice = np.zeros(2)
masschoice = achoice
agechoice = achoice

for u in range (0, 2):

    achoice[u] = np.random.choice(a_onc)
    print(achoice[u])

    masschoice[u] = np.random.choice(mass_onc)
    print(achoice[u], masschoice[u])

    agechoice[u] = np.random.choice(age_onc)
    print(achoice[u], masschoice[u], agechoice[u])

    print("")

以下是输出:

1.0
12.0 12.0
21.0 21.0 21.0

5.0
11.0 11.0
23.0 23.0 23.0

正如您所注意到的,从'a_onc'数组中选择的随机值是1和5(在循环的两次运行中)。它们被储存在“achoice”阵列中。但是,当从mass\onc中选择随机值时,“achoice”中的值也会改变

有人能告诉我怎么处理这个问题吗


Tags: 代码importnumpyagenprandom数组array