Learn python list generation type, so that your code is "show up"
the list of Formula
• As the name implies, a listing of formula is a particular form of expression syntax used to generate a list.
For example, we need to generate a list consisting of 0-9, then we can write:
List1 = [0,1,2,3,4,5,6,7,8,9]
feeling, manually writing this 10 digital Fortunately, however, sometimes, what, this manual testing algorithm or function to write is not tired ?? is there a more convenient way.? there.
first, let's introduce the range.
What • range have effect
- range () function creates a list of integers, generally used in a for loop.
Function Syntax range (start, stop [, step ])
Parameters:
• start: start counting from the beginning. The default is zero. E.g. range (5) is equivalent to Range (0,. 5);
• stop: stop counting to the end, but not stop. For example: range (0, 5) is [0, 1, 2, 3, 4] no. 5
• STEP: step size, default is one. For example: range (0, 5) is equivalent to the range (0, 5, 1) Example
range (10) # from 0 to 10
[0, 1, 2, 3,. 4,. 5,. 6,. 7,. 8,. 9]
Range (1, 11) # starting from 1 to 11
[1, 2, 3, . 4,. 5,. 6,. 7,. 8,. 9, 10]
Range (0, 30,. 5) # in steps. 5
[0,. 5, 10, 15, 20 is, 25]
Range (0, 10,. 3) # step length. 3
[0,. 3,. 6,. 9]
Range (0, -10, -1) negative #
[0, -1, -2, -3, -4, -5, -6, -7, -8 , -9]
Range (0)
[]
Range (. 1, 0)
[]
through the use range, can quickly generate a list of the order
Then, things are not so simple. If I need to list each element of which special treatment, for example, addition and subtraction, then, how to deal with it?
- Use for operation again.
- .. Draw a list of key generative
base syntax [exp for iter_var in iterable]
work process:
• iteration of each element in the iterable;
• the results of each iteration are first assigned to iter_var, then get a new calculation by exp value;
• Finally, all calculated values obtained by exp return to a form of the new list.
This process corresponds to:
L = []
for iter_var in Iterable:
L.append (exp)
nested loop syntax [exp for iter_var_A in iterable_A for iter_var_B in iterable_B]
Working procedure:
a • element in each iteration iterable_A, it all the elements are in ierable_B iteration again.
This process corresponds to:
L = []
for iter_var_A in iterable_A:
for iter_var_B in iterable_B:
L.append (exp)