蟒蛇。在循环中填充数组 [英] Python. Filling array in the loop

查看:60
本文介绍了蟒蛇。在循环中填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建2d数组并将其填充到循环中。
我知道我需要多少行,但是我不知道循环后每一行的大小。
在C ++中,我可以使用:

I need to create 2d array and fill it in the loop. I know how many rows I need, but I don't know what size each row will be after the loop. In C++ I can use:

vector<vector<int>> my_vec(3);
my_vec[0].push_back(1);
my_vec[0].push_back(2);
my_vec[1].push_back(3);
my_vec[2].push_back(4);

我将有:

1 2

3

4

And I will have:
1 2
3
4

但是当我尝试python时:

But when I try python:

aa = [[] * 0] * 3
aa[0].append(5)
aa

输出是:[[5],[5],[5]]

output is: [[5], [5], [5]]

我认为这是python的方式创建数组,所有单元都引用相同的内存点。对?这就是为什么如果我给aa [0] = [1,2]分配一些新值,那么我可以追加到aa [0]上,并且不会影响其他行。

I think it's how python creates array, all cells reference to the same memory spot. Right? That's why if I assign some new value to aa[0] = [1,2], then I can append to aa[0] and it will not affect other rows.

那么我该如何解决呢?创建一个空数组,然后填充它,将元素一一添加到我需要的行。
我可以使用numpy数组。
谢谢。

So how I can solve this? Create empty array, then fill it adding elements one by one to the row I need. I can use numpy array. Thank you.

推荐答案

将列表与数字相乘得到的列表是正确的以及对同一列表的许多引用,并且当您修改一个元素时,您同时修改了所有元素,要解决该问题,您可以尝试使用列表理解:

you are right when you multiply a list of lists with a number you are getting one list and many references to the same list and when you are modifying one element you are modifying all, to solve the issue you can try using list comprehension:

aa = [[] for _ in range(3)]

或for循环:

aa = []

for _ in range(3):
    aa.append([])

这篇关于蟒蛇。在循环中填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆