How to define an array of large lists in Python using For loop or Vectorization?

I have a 2D list of 416 rows, each row contains 4 columns. Lines 1-4 contain the line number 4 times (ie, [...[1,1,1,1],[2,2,2,2]...] . Line 330 contains [41,22,13,13] . Everything else is [0,0,0,0] . I am currently using a for loop with many explicit if statements.

 myList = [[0,0,0,0]] for i in range(1, 416): if i == 1 or i == 2 or i == 3 or i == 4: myList.append([i,i,i,i]) elif i == 330: myList.append([41,22,13,13]) else: myList.append([0,0,0,0]) 

What is a more efficient way to define this array?

The other questions that I saw on SO do not seem to explicitly address this question, but if someone finds one that can be considered a duplicate, mark this question as such, and I will accept it.

+5
source share
2 answers

Since the bulk of the list is a list of zeros (in terms of an array sparse), I will simply reassign and then use the slice assignment / indexing to update:

 my_list = [[0, 0, 0, 0] for _ in range(416)] my_list[330] = [41,22,13,13] my_list[1:5] = [[i]*4 for i in range(1, 5)] 

This avoids re-evaluating the branches for many false cases and repeated additions.

OTOH, having zeros throughout your memory, can be avoided if you actually save the data structure as a sparse matrix. You could take a look at the SciPy 2-D sparse matrix package .

+7
source

On top of my head, a really easy and quick way to do this:

 import itertools answer = list(itertools.chain([[i,i,i,i] for i in range(1,5)], [[0,0,0,0] for _ in range(330-6)], [[41,22,13,13]], [[0,0,0,0] for _ in range(416-330)])) 
+1
source

Source: https://habr.com/ru/post/1269758/


All Articles