简体   繁体   English

创建N个长度为M的数组,其中每个数组的序列加1

[英]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.

相关问题 从 N 和 M 大小的 2 个数组/列表创建 NxM 数组 - Create NxM array from 2 arrays/lists of N and M size 将长度为 N 的序列切割成子序列,使得每个子数组的和小于 M 并且切割最小化每个部分的最大值之和 - Cut a sequence of length N into subsequences such that the sum of each subarray is less than M and the cut minimizes the sum of max of each part 从长度为n的序列中选择m个等距元素 - Choose m evenly spaced elements from a sequence of length n Python:如何生成一个序列,每个 m 个数字跳过 n 个数字 - Python: How to generate a sequence skipping n numbers each m numbers 在m个字符的列表中找到n个不同的字符序列的每次出现 - Find each occurrence of n different sequence of characters in a list of m characters numpy可以通过将一维数组中的n个元素与另一个一维数组的每个元素相加来创建n个数组吗? - Can numpy create n arrays by summing n elements in 1d array to each element of another 1d array? Numpy 来自数组,为每个元素创建一个矩阵 N*M ,所有值都设置为没有 for 循环的元素 - Numpy from an array, for each element create a matrix N*M with all values set as the element without for loops 如何将每个 for 循环中的新行添加到数组,以便在 python 中创建矩阵 (m,n)? - How to add new rows in each for loop to an array in order to create a matrix (m,n) in python? 从数组和 boolean “共享”数组创建 m*n arrays - Creating m*n arrays from an array and a boolean "shared" array 用中间数组的M个长度排列N个列表的所有可能 - Permutate all posibilities for N lists with M length of middle array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM