字符串的Numpy数组同时具有字符串和数组

2024-04-27 11:28:41 发布

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

我创建了如下数组: current_pop = np.full(N, "W", dtype = object) 并使用for循环{}在当前_pop上迭代

当我print(current_pop[i])时,我通常会得到“W”,但偶尔会得到[“W”],这会把我的程序搞砸

完整代码如下:

#Table
populations_index = {
    'W' : 0,
    'A' : 0,
    'B' : 0,
    'C' : 0
}



#initialize our population of 100
N = 100
current_pop = np.full(N, "W", dtype = object)

#create our probabiliy vector
mutant_prob_dictionary = {
    "A" : 0.01, 
    "B" : 0.015,
    "C" : 0.018
}

trials = np.arange(0, 501, 1)


for t in trials:
    #every time I need to refresh prob and mutant list
    mutant_p = [mutant_prob_dictionary['A'], mutant_prob_dictionary['B'],mutant_prob_dictionary['C']]
    mutant = ['A','B','C']
    assert(len(mutant) == 3)

    #run through each cell
    for i in np.arange(0, len(current_pop)):

        #ERROR HERE:
        assert(type(current_pop[i]) == str)


        if current_pop[i][0] == "W":
            wild_prob = 1 - np.sum(mutant_p)
            mutant_p.append(wild_prob) #add wild prob at the end
            prob_vector = mutant_p

            mutant.append('W') #add wild self to end
            species_vector = mutant
            assert(np.sum(prob_vector) == 1)
        else: #must be mutant

            mutant_p.remove(mutant_prob_dictionary[current_pop[i][0]]) #remove its prob
            mutant.remove(current_pop[i][0]) #remove itself
            own_prob = 1 - np.sum(mutant_p)
            mutant_p.append(own_prob) #add its prob at the end
            mutant.append(current_pop[i][0]) #add itself at the end

            prob_vector = mutant_p
            species_vector = mutant

        #Now I have a probability vector and a species vector
        #draw a cell based off the mutation prob
        new_cell = np.random.choice(species_vector, size = 1, p = prob_vector)
        print(current_pop[i])

        current_pop[i] = new_cell

    for s in list(populations_index): #iterate for each species
        populations_index[s] = list(current_pop).count(s) #adds the population count of that species

Tags: theaddfordictionarynpcellcurrentpop
1条回答
网友
1楼 · 发布于 2024-04-27 11:28:41

您的错误是由于这一行

current_pop[i] = new_cell

变量new_cell实际上是一个包含一个元素的列表:['W']

您正在将其分配给current_pop,这意味着是一个字符串列表

一旦内部循环完成,即i到达99,外部循环开始第二次迭代,i返回为0。但是current_pop[0]现在是您之前设置的['W']。因此,产生了错误

要解决此问题,请确保您正在将一个字符串分配回current_pop列表,例如

current_pop[i] = new_cell[0][0]

相关问题 更多 >