List understanding
A common application is to make a new list where each element is the result of a number of actions that are applied to each member or iteration of another sequence, or create a new list that satisfies the criteria for those elements:
#List comprehensions
"" "Common applications is to make new lists where each element is the result of some ope Rations applied to
each member of another sequence or iterable, or to create a subsequence of those elements the
SA Tisfy a certain condition. "" "
Squares = []
for x in range:
Squares.append (x**2)
Print (squares)
Print (x)
"" Note That this creates (or overwrites) a variable named X that still exists after the loop completes.
We can calculate the list of squares without any side effects using: "" "
Squares1 = List (map (lambda y:y**2, range (1 0))
Print (squares1)
#print (y) err:y is not defined
Squares3 = [z** 2 for z in range
Print (SQUARES3)
#print (z) err:z are not defined
run Result:
D:\Python3.6.1\python.exe f:/python_workspace/tutorial/lists3.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
9
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Process finished with exit code 0
A list expression containing [] can pass through a for statement through 0 or more for or if statements.
Then zero or more for or if clauses. """
RESULT1 = [(x, Y) for x in [All-in-A-z] for y in [3,1,4] if x! = y]
Print (RESULT1)
i = j = 0
while (I < 7):
Print ("-------------------")
while (J < 2):
Print (Result1[i][j])
j = j + 1
j = 0
i = i +1
Continue
Operation Result:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
-------------------
1
3
-------------------
1
4
-------------------
2
3
-------------------
2
1
-------------------
2
4
-------------------
3
1
-------------------
3
4
Study reference: Https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
Basic Python Learning (vi)