Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cleaner way than using for loops

Tags:

python

numpy

I would like to know if there are any other ways to loop and manipulate data located in separate arrays.

import numpy as np

a = np.arange(2)
b = np.arange(5)
c = np.arange(5)

l1 = []
for x in a:
    l2 = []
    for y in b: 
        l3 = []
        y = x + 1  
        for z in c:
            z = x + y
            t = (x,y,z)
            l3.append(t)
        l2.append(l3)
    l1.append(l2) 
print l1
like image 569
Wallace Avatar asked Jan 01 '26 08:01

Wallace


1 Answers

This code does exactly what you are doing.

def method(lst, range1, range2):
    for i in lst:
        yield [[(i, i+1, 1+(i*2))]*range2]*range1

Can even be turned into a generator expression:

def gen_method(lst, r1, r2):
    return ([[(i, i+1, 1+(i*2))]*r2]*r1 for i in lst)

Test it yourself if you like.


My tests:

a = range(2)
b = range(5)
c = range(5)

def your_method(a, b, c):
    l1 = []
    for x in a:
        l2 = []
        for y in b: 
            l3 = []
            y = x + 1  
            for z in c:
                z = x + y
                t = (x,y,z)
                l3.append(t)
            l2.append(l3)
        l1.append(l2)
    return l1

def my_method(lst, range1, range2):
    for i in lst:
        yield [[(i, i+1, 1+(i*2))]*range2]*range1

yours = your_method(a, b, c)
mine = list(my_method(a, len(b), len(c)))

print yours
print '==='
print mine
print '==='
print yours == mine

>>> 
[[[(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)]], [[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]]]
===
[[[(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)]], [[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]]]
===
True
like image 118
Inbar Rose Avatar answered Jan 03 '26 22:01

Inbar Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!