Carlos Muñiz
Carlos Muñiz

Reputation: 1918

How to create a numpy list from within a loop

I have a numpy list of arrays (a two-dimensional list):

db = [ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10, ch11, ch12, ch13, ch14, ch15, ch16]

I would like to perform some operations in these arrays like this:

for i in db:
    newch = (eegFilter(i)/sens)+25

How can I create a new two-dimensional list with the results of each loop iteration so that the new array would look something like this:

[[newch_iteration_1], [newch_iteration_2], [newch_iteration_3], ....]

Upvotes: 0

Views: 114

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

Use a list comprehension:

[((eegFilter(i)/sens)+25).reshape(1, *i.shape) for i in db]

Demo:

In [12]: db = [np.arange(10).reshape(2, 5), np.arange(12).reshape(3, 4)]

In [13]: [(x%2).reshape(1, *x.shape) for x in db]                                                
Out[13]: 
[array([[[0, 1, 0, 1, 0],                                                                        
        [1, 0, 1, 0, 1]]]),                                                                      
 array([[[0, 1, 0, 1],                                                                           
        [0, 1, 0, 1],                                                                            
        [0, 1, 0, 1]]])]   

Upvotes: 1

Related Questions