[英]Create N arrays of length M where the sequence is increased by 1 on each array
Good morning, 早上好,
Given two numbers (a,b), I should create 'a' different list of length 'b' where the sequence of each list is increased by one. 给定两个数字(a,b),我应该创建一个长度为'b'的'a'不同列表,其中每个列表的顺序加一。
For example : 例如 :
1,2 => [[0,1]]
1,2 => [[0,1]]
2,2 = > [[0,1], [1,2]]
2,2 => [[0,1], [1,2]]
I am trying to write the following function: 我正在尝试编写以下功能:
def increase_arrays(arrays, length):
result = [[i for i in range(length)] for i in range(arrays)]
return result
increase_arrays(2,3)
=> [[0, 1, 2], [0, 1, 2]]
I can't see how to modify my code so the second array is [1,2,3]
. 我看不到如何修改代码,所以第二个数组是[1,2,3]
。 Could anyone help to resolve the issue? 谁能帮助解决问题?
You have famous duplicated index problem, you have 2 indexes i
. 您有著名的重复索引问题,您有2个索引i
。
Below is the code that you need: 下面是您需要的代码:
def increase_arrays(arrays, length):
result = [[i + j for i in range(length)] for j in range(arrays)]
return result
increase_arrays(2, 3)
returns [[0, 1, 2], [1, 2, 3]]
increase_arrays(2, 3)
返回[[0, 1, 2], [1, 2, 3]]
I finally managed to solve it with: 我终于设法解决了:
def increase_arrays(arrays, length):
return [list(range(i,length+i)) for i in range(arrays)]
这是一个很有趣的解决方案,只是为了好玩:
np.arange(arrays)[:,np.newaxis] + np.arange(length)[np.newaxis,:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.