This example describes the use of the list loop statement in Python. Share to everyone for your reference. The specific usage analysis is as follows:
One of the powerful features of Python is its parsing of the list, which provides a compact way to map a list to another list by applying a function to each element in the list.
Instance
Copy Code code as follows:
A = [' Cat ', ' window ', ' defenestrate ']
For X in a:
Print x, Len (x)
For x in [1, 2, 3]: print x, # iteration Loop through a list:for
A = [' Cat ', ' window ', ' defenestrate ']
For x in a[:]: # Make a slice copy of the entire list
If Len (x) > 6:a.insert (0, X)
Print a
Run Result:
Copy Code code as follows:
Cat 3
Window 6
Defenestrate 12
1 2 3 [' defenestrate ', ' Cat ', ' window ', ' defenestrate ']
To operate according to the length of an array:
Copy Code code as follows:
A = [' Mary ', ' had ', ' a ', ' little ', ' lamb ']
For I in range (Len (a)):
Print I, A[i]
Run Result:
Copy Code code as follows:
0 Mary
1 had
2 A
3 Little
4 Lamb
Copy Code code as follows:
words = [' A ', ' B ', ' C ', ' D ', ' E ']
For word in words:
Print Word
Run Result:
Copy Code code as follows:
List Resolution Introduction:
Copy Code code as follows:
>>> Li = [1, 9, 8, 4]
>>> [elem*2 for Elem in Li]
[2, 18, 16, 8]
>>> Li
[1, 9, 8, 4]
>>> Li = [elem*2 for Elem in Li]
>>> Li
[2, 18, 16, 8]
To make it easier to understand, let's look at it from right to left. Li is a list that will be mapped. Python loops through each element in the LI. For each element, you first assign the value to the variable elem, and then Python applies the function elem*2 to the calculation, and then appends the result to the list to be returned.
It should be noted that the parsing of the list does not change the original list.
It is safe to assign the parse result of a list to the variable to which it is mapped. There's no need to worry about competition or any weird thing happening. Python creates a new list in memory, and Python assigns the result to a variable when parsing the list is complete.
I hope this article will help you with your Python programming.