如何在python中使用for循环附加多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43291165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append multi dimensional array using for loop in python
提问by Eka
I am trying to appendto a multi-dimensional array.
我正在尝试append一个多维数组。
This is what I have done so far:
这是我到目前为止所做的:
arr=[[]]
for i in range(10):
for j in range(5):
arr[i].append(i*j)
print i,i*j
print arr
This is my expected output:
这是我的预期输出:
[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12],[0,4,8,12,16],[0,5,10,15,20],[0,6,12,18,24],[0,7,14,21,28],[0,8,16,24,32],[0,9,18,27,36]]
[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12],[0,4,8,12,16],[0,5,10,15,20],[0,6,12,18,24],[0,7,14,21,28],[0,8,16,24,32],[0,9,18,27,36]]
However, I am getting this error:
但是,我收到此错误:
IndexError: list index out of range
IndexError: 列表索引超出范围
采纳答案by vallentin
You're forgetting to append the empty list beforehand. Thus why you get a, IndexErrorwhen you try to do arr[i].
您忘记预先附加空列表。因此,IndexError当您尝试执行arr[i].
arr = []
for i in range(10):
arr.append([])
for j in range(5):
arr[i].append(i*j)
回答by Miriam Farber
You need to define your initial array in the following way: arr=[[] for i in range(10)], as you cannot append a value to a nonexistent array (which is what happens when i>=1). So the code should look like:
您需要按以下方式定义初始数组:arr=[[] for i in range(10)],因为您不能将值附加到不存在的数组(当 时会发生这种情况i>=1)。所以代码应该是这样的:
arr=[[] for i in range(10)]
for i in range(10):
for j in range(5):
arr[i].append(i*j)
print(i,i*j)
print(arr)
回答by gyre
As others have pointed out, you need to make sure your list of lists is initially populated with ten empty lists (as opposed to just one) in order for successive elements to be appended correctly.
正如其他人指出的那样,您需要确保您的列表列表最初填充了十个空列表(而不是只有一个),以便append正确编辑连续元素。
However, I might suggest using a terser nested list comprehension instead, which avoids the problem entirely by creating the list in a single statement:
但是,我可能会建议使用更简洁的嵌套列表推导式,它通过在单个语句中创建列表来完全避免问题:
arr = [[i*j for j in range(5)] for i in range(10)]
回答by shizhz
You init your arras an arraywith only 1 element, so you have such an error when igoes greater than 0. You can use list comprehensiveto archive your purpose:
您将您的arras an初始化为array只有 1 个元素,因此当i大于0. 您可以使用list comprehensive归档您的目的:
[[i * j for j in range(5)] for i in range(10)]

