3
votes

The following Python List Comprehension statement could be rephrased as the for loop below.

>>> [(x,y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1]

>>> result = []
>>> for x in range(5):
    if x % 2 == 0:
        for y in range(5):
            if y % 2 == 1:
                result.append((x,y))

I'm having hard time understanding the following two list comprehension expressions.
What is the equivalent for loop(easier to read) way of expressing them?

[(min([row[i] for row in rows]),max([row[i] for row in rows])) 
for i in range(len(rows[0]))]

[[random.random()*(ranges[i][1]-ranges[i][0])+ranges[i][0] 
for i in range(len(rows[0]))] for j in range(k)]
2
The first one is accessing a matrix and performing min and max on the values on each cell in the matrix. I am posting this as comment beacuse others where faster than me. - rapadura
That range(len(x)) construct is horribly un-Pythonic. - Karl Knechtel

2 Answers

3
votes

To use your style:

I believe the first one does this:

result = []
for col in range(len(rows[0])):
    a = rows[0][col]
    b = rows[0][col]
    for row in rows:
        a = min(a, row[col])
        b = max(b, row[col])

    result.append((a, b))
1
votes

Here is an example to expand the first loop , see it here : http://codepad.org/cn0UFPrD

rows = [[1,2,3,4],[3,5,88,9],[4,55,-6,0],[0,34,22,1222]]
t1 = [(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))]
print(t1)

# Easy loop
t2 = []
for i in range(len(rows[0])):
    innerElements = []
    for row in rows:
        innerElements.append(row[i])
    newTuple = ( min(innerElements),max(innerElements) )
    t2.append(newTuple)

print(t2)

You can expand the second loop the same way.