1 List-derived definitions
The list derivation can be very concise to construct a new list: The resulting element can be transformed with a simple expression
2 List derivation syntax
The basic format is as follows:
[Expr for value in collection if condition]
Filter conditions are optional, depending on the actual application, leaving only the expression
Example of a list derivation:
| 12 |
l=["egg%s"%i fori inrange(10)]print(l) |
Similar to this for code:
| 1234 |
egg_list=[]fori inrange(10): egg_list.append("egg%s"%i)print(egg_list) |
The list derivation can also add more if to judge the For loop
| 1234 |
l=[‘egg%s‘%i fori inrange(1,101)]l=[‘egg%s‘%i fori inrange(1,101) ifi >50]l=[‘egg%s‘%i fori inrange(1,101) ifi >50 ifi<60]print(l) |
3 List Derivation Benefits
Convenient, change the programming habit, belong to the declarative programming
Example:
| 1234 |
l=[1,2,3,4]s="hello"l1=[(num,i) fornum inl fori ins]print(l1) |
The output is:
| 1 |
[(1, ‘h‘), (1, ‘e‘), (1, ‘l‘), (1, ‘l‘), (1, ‘o‘), (2, ‘h‘), (2, ‘e‘), (2, ‘l‘), (2, ‘l‘), <br>(2, ‘o‘), (3, ‘h‘), (3, ‘e‘), (3, ‘l‘), (3, ‘l‘), (3, ‘o‘), (4, ‘h‘), (4, ‘e‘), (4, ‘l‘), <br>(4, ‘l‘), (4, ‘o‘)] |
This list derivation is equivalent to:
| 12345678 |
l=[1,2,3,4]s="hello"l1=[]fornum inl: fori ins: t=(num,i) l1.append(t)print(l1) |
4 Examples of list expressions
| 1234567891011 |
importosg=os.walk("C:\python_fullstack_wen\day24\wen")file_path_list=[]fori ing: forj ini[-1]: file_path_list.append("%s\\%s"%(i[0],j))print(file_path_list)g=os.walk("C:\python_fullstack_wen\day24\wen")file_path_list=["%s\\%s"%(i[0],j) fori ing forj ini[-1]]print(file_path_list) |
Output Result:
| 12 |
[‘C:\\python_fullstack_wen\\day24\\wen\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen1<br>\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\jie1\\yan1.txt‘, <br>‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1\\yan1.txt‘, <br>‘C:\\python_fullstack_wen\\day24\\wen\\wen2\\yan2.txt‘][‘C:\\python_fullstack_wen\\day24\\wen\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\jie1\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1\\yan1.txt‘, ‘C:\\python_fullstack_wen\\day24\\wen\\wen2\\yan2.txt‘] |
Python list derivation