Equivalent to loop expressions for a comprehensive list comprehension

The following Python List Comprehension statement can be rephrased as a 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 find it difficult to understand the following two expressions of understanding the context.
What is equivalent to a loop (easier to read) to express 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
python for-loop list-comprehension
Nov 08 2018-11-11T00:
source share
2 answers

Here is an example of extending the first loop, see 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 in the same way.

+1
Nov 08 2018-11-11T00:
source share

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)) 
+3
Nov 08 2018-11-11T00:
source share



All Articles