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

时间:2018-07-12 01:45:43

标签: python python-3.x numpy

我创建了一个像这样的数组:       current_pop = np.full(N, "W", dtype = object) 并使用for循环for i in np.arange(0, len(current_pop)):遍历current_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

1 个答案:

答案 0 :(得分:0)

您的错误是由于此行

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]