Reprint to: http://blog.csdn.net/watermusicyes/article/details/43762551
In Python, list generation is an expression that makes it easy to build lists. Sometimes it can replace list.append ().
What if you want to build [1*1, 2*2, 3*3, ..., 10*10]? You can use loops:
>>> l= []>>> for x in range (1, ten): ... L.append (x*x) ... >>> l[1, 4, 9, 16, 25, 36, 49, 64, 81]
and list generation, you can use a sentence instead of the tedious loop above to complete the above operation:
List-Generated writing format: [x*x for X in range (1, 11)]
First: Put the elements you want to create x*x to the front
Second: Follow the For loop
This allows the list to be created.
The For loop can also be followed by an if judgment, so that even squares can be filtered out:
Of course, you can use a two-layer loop to generate a full array:
How to use two variables to generate a list:
D = {' Java ': "}l", ' C ': "", "" The "," C + + ":" The "" The "" The "" +v "=" k + ' = ' "for K, V in D.iteritems ()]print L
Python List-generated