如何在c#中的列表中更改2D数组中特定项的值

时间:2018-04-27 13:57:32

标签: c# list

我尝试将列表项更改为2D数组列表,如下所示,但我认为这是一种错误的方式,因为我的应用程序在调用此代码段时没有响应:

background.paste(img, offset)
AttributeError: 'numpy.ndarray' object has no attribute 'paste'

我需要知道为什么我的应用在调用此方法时没有响应?

2 个答案:

答案 0 :(得分:0)

请参阅评论

In [1]: import numpy as np

In [2]: cvector = [np.zeros([6, 3])]*2

In [3]: cvector
Out[3]: 
[array([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]), 
 array([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])]

In [4]: cvector[0][0] = (1, 2, 3)

In [5]: cvector
Out[5]: 
[array([[1., 2., 3.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]), 
 array([[1., 2., 3.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])]

答案 1 :(得分:0)

我还没有完成对整个代码示例的审核,但我确实注意到了一件事。看看Random()

的这种用法
rndNumber1 = rnd.Next(0, 10) / 100; // generate a random number between 0 and 10 and divide result by 100
if (rndNumber1 <= Pm) /* check if we will do Crossover */
{
    //...
}

这里有几个错误最终会导致意想不到的结果。第一个是rnd.Next()的上限是独占。这意味着rnd.Next()调用将产生09的结果。它永远不会是10,这与该行旁边的评论相反。 (同样的错误也是在这段代码中使用Random的其他用法)。

接下来要理解的是我们在这里完全使用整数。这包括进行整数除法,它将丢弃结果的任何小数部分。因此,当我们将0到9(或甚至0到10)范围内的数字除以100时,结果是 .00.09.00.10。结果是 0 。将rndNumber1声明为double是不够的。在赋值给double变量之前,确定除法表达式的整数结果。

换句话说,无论rnd.Next()来电何时返回,rndNumber1 始终最终都会 0 。< / p>

现在去检查下一行,我怀疑0总是小于Pm值。这意味着代码将在if()块中运行(可能)昂贵的计算,用于所有的populuation中的记录,当你看起来真的只想做大约5百分之记录。那可能解释为什么花了这么长时间。

进一步阅读代码还表明,当它可以直接引用该行时,它会检查染色体中每一行的随机数匹配。该修复程序还将有助于代码运行得更快。

//No need to return anything. The population mutation will be seen by the caller.
//Additionally, the Roullette wheel was never used.
public void Mutation(IEnumerable<int[,]> population)
{
    Random rnd = new Random();

    foreach(int[,] chromosome in population)
    {
        double selectionFactor = rnd.Next(0, 11) / 100.0D; // generate a random number between 0 and 10 and divide result by 100
        //Pm could be passed to the method as an argument
        if (selectionFactor <= Pm) /* check if we will do Crossover */
        {
            int crossoverRow = rnd.Next(0, chromosome.GetLength(0)); 
            int columns = chromosome.GetLength(1);
            for(int c = 0; c < columns; c++)
            {
                if (chromosome[crossoverRow, c] == 0)
                {
                    chromosome[crossoverRow, c]  = 1;
                }
            }
        }
    }
}

<强>更新

问题中的代码已经改变,现在比以前更没意义了。 人口中的每个项目都有一个循环

 for (int i = 0; i < population.Count; i++)

但该代码中i 从未使用过。至少现在使用RouletteWheel,但仅用于限制最多的前9个项目。那......不对。甚至没有关闭。