Priya Ramakrishnan
Priya Ramakrishnan

Reputation: 45

how to create a multidimensional array on the fly using python?

I have a loop which generates a value_list each time it runs, at the end of each iteration i want to append all the lists into a one multi dimensional array

I have:

At the end of each iteration I want one multi dimensional array like

How could I achieve this?

Thanks

Upvotes: 1

Views: 698

Answers (6)

Anonymous
Anonymous

Reputation: 4632

(lambda x,y: np.arange(1,1+x*y).reshape((x,y)).tolist())(3,4)

Upvotes: 0

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

Try this below :

value_list_copy = []

for i in range(n): # ----------> Assuming n is the number of times your loop is running
    value_list_copy.append(value_list)  # ------ Append your value list in value_list_copy in every iteration

Here you will get an array of arrays.

print(value_list_copy)

Upvotes: 0

user2390182
user2390182

Reputation: 73460

You can use a nested comprehension and itertools.count:

from itertools import count, islice

cols = 4
rows = 5

c = count(1)
matrix = [[next(c) for _ in range(cols)] for _ in range(rows)]
# [[1, 2, 3, 4], 
#  [5, 6, 7, 8], 
#  [9, 10, 11, 12], 
#  [13, 14, 15, 16], 
#  [17, 18, 19, 20]]

The cool kids might also want to zip the count iterator with itself:

list(islice(zip(*[c]*cols), rows))
# [(1, 2, 3, 4), 
#  (5, 6, 7, 8), 
#  (9, 10, 11, 12), 
#  (13, 14, 15, 16), 
#  (17, 18, 19, 20)]

Upvotes: 3

Phillyclause89
Phillyclause89

Reputation: 680

Here are two other possible solutions:

Double for loop approach

rows, cols, start = 3, 4, 1

value_list_copy = []
for j in range(rows):
    value_list = []
    for i in range(start, cols + start):
        value_list.append((j*cols)+i)
    value_list_copy.append(value_list)
    print(
        f'value_list = {value_list}\n'
        f'value_list_copy = {value_list_copy}\n'
    )

List comp method

rows, cols, start = 3, 4, 1

value_list_copy_2 = [
    [
        (j*cols)+i for i in range(start, cols + start)
    ] for j in range(rows)
]
print(f'value_list_copy_2 = {value_list_copy_2}')

Python Tutor Link to example code

Upvotes: 0

Ketan Krishna Patil
Ketan Krishna Patil

Reputation: 81

Try this:

limit = 10
length_of_elements_in_each_list = 4
[range(i, i+length_of_elements_in_each_list) for i in range(1, limit)]

You can set a limit and length_of_elements_in_each_list according to your need.

Upvotes: 1

Ch3steR
Ch3steR

Reputation: 20669

If you are using Python3.8 then use Walrus assignment(:=).

For Syntax and semantic.

count=0
rows=5
cols=4
[[(count:=count+1) for _ in range(cols)] for _ in range(rows)]

Output:

[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12],
 [13, 14, 15, 16],
 [17, 18, 19, 20]]

Without using :=.

rows=5
cols=4
[list(range(i,i+cols)) for i in range(1,rows*cols,cols)]

Upvotes: 1

Related Questions