At the moment my code is as follows
A = [matrix_x[i][:n] for i in xrange(0, n)]
B = [matrix_x[i][n:] for i in xrange(0, n)]
C = [matrix_x[i+n][:n] for i in xrange(0, n)]
D = [matrix_x[i+n][n:] for i in xrange(0, n)]
Is there a better way of doing this, since I am continually looping over the same xrange. In this instance, would if be better to not use a list comprehension and just append the values to each list while in a single for loop.
A,B,C,D = [],[],[],[]
for i in xrange(0,n):
A.append(matrix_x[i][:n])
B.append(matrix_x[i][n:])
... etc
Second way seems more efficient to me. What way would be more ‘pythonic’ or is there another way I haven’t thought of
I generally prefer to iterate over the list of items itself, rather than over
xrange(len(list_of_items))and working with the i’th item at a time. Here’s how to usezipto look at each(this,next)pair in a sequence, and then build up your lists:And yes, you can really compact this down to a
zipof azip: