List generation can automatically generate a list without having to define it manually.
By the way, the range function, the range function is in range (Start,stop,step), and the parameter is starting, terminating, but not containing, spaced. Range (1,10,1) gets 1-9 of these 9 digits.
If the list produces consecutive numbers, you can use the range function to complete
L=list (range (0,10,1))
Print (L)
Back to List 1-9
If you generate a list of 1*1,2*2 ... it's more troublesome.
L=[]
For I in Range (1,11,1):
L.append (I*i)
Print (L)
Returns a list of 1*1,2*2...10*10
If you are using a list-generation
L=[x*x for x in range (1,11)]
Print (L)
Can be understood separately, l=[x*x], followed by the value range of X.
You can also add a condition in a list-generation
L=[x*x for x in range (1,11) if x%2==0]
Print (L)
The square of an even number in 1-10.
A string is also considered a list, so you can also cycle through the list in two tiers
L=[x+y for x in ' Abcde ' to Y in ' fghij ']
Print (L)
Back [' af ', ' AG ', ' ah ', ' ai ', ' aj ', ' BF ', ' bg ', ' bh ', ' bi ', ' bj ', ' CF ', ' CG ', ' ch ', '
Ci ', ' CJ ', ' DF ', ' DG ', ' dh ', ' di ', ' DJ ', ' ef ', ' eg ', ' eh ', ' ei ', ' ej '
List-Generated writing format: [x*x for X in range (1, 11)]
First: Put the elements to be generated x*x to the front
Second: Follow up for loop
So you can create the list.
The For loop can also be followed by an if judgment, which filters out even squares:
>>> [x*x for x in range (1, one) if x%2 = = 0]
[4, 16, 36, 64, 100]
>>>
Of course, you can use a two-tier loop to generate a full arrangement:
>>> Print [M + N for M with ' ABCD ' for n in ' XYZ ']
[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ', ' DX ', ' DY ', ' DZ ']
>>>
>>> How to use two variables to generate a list:
D = {' Java ': "The", "C": "," "C + +": "99"}
L = [k + ' = ' +v for K, V in D.iteritems ()]
Print L
Finally, do an exercise:
L = [' Java ', ' C ', ' Swift ', ' Python ', 123], now has a list containing strings, and integers, to the list of uppercase characters into lowercase, pushed out of another list ":
1, using the built-in Isinstance function can determine whether a variable is a string
2, S.lower () can convert a capital letter to lowercase.
3, increase the IF statement to ensure that the list generated correct execution.
The code is as follows:
L = [' Java ', ' C ', ' Swift ', ' Python ', 123]
Print [S.lower () if isinstance (S, str) else s for s in L]