Catalog
List generator
List generated case 1
List generated case 2
List generated case 3
List generated case 4
List generated case 5
iterator (Iterator)
Iteratable object :Iterable
iterator :Iterator
iter() function
Summary
List generation is List Comprehensions:
yes Python Built in very simple but powerful can be used to create list Generative form of .
To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
It can be used list(range(1, 11)):
list(range(1, 11))
The result is :[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But if you want to generate [1x1, 2x2, 3x3, ..., 10x10] How do you do it? ?
The first method is circulation :
L = []
for x in range(1, 11):
L.append(x * x)
The result is :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But the cycle is too complicated ,
List generation can use a single line of statements instead of loop generation list:
[x * x for x in range(1, 11)]
The result is :[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
When writing list generation , Put the elements to be generated x * x Put it in front , Followed by for loop , You can put the list created , Simple 、 convenient .
for You can also add if Judge :
So we can filter out only even squares :
[x * x for x in range(1, 11) if x % 2 == 0]
The result is :[4, 16, 36, 64, 100]
Can generate a full permutation :
[m + n for m in 'ABC' for n in 'XYZ']
The result is :['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
Use list generation , Can write very simple code .
for example , List all files and directory names in the current directory , It can be implemented in one line of code :
Be careful :os.listdir You can list files and directories
import os # Import os modular , The concept of modules is discussed later
[d for d in os.listdir('.')]
for Loops can actually use two or more variables at the same time , such as dict Of items() You can iterate at the same time key and value:
d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
print(k, '=', v)
The result is :y = B x = A z = C
therefore , List generation can also use two variables to generate list:
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()]
The result is :['y=B', 'x=A', 'z=C']
Put one list All strings in are lowercase :
L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
The result is :['hello', 'world', 'ibm', 'apple']
Can act directly on for The data types of the loop are as follows :
One is set data type , Such as list、tuple、dict、set、str etc. ; One is generator, Including generator and belt yield Of generator function.
These can act directly on for Circular objects are collectively called iteratable objects :Iterable.
have access to isinstance() Determine whether an object is Iterable object :
And generators can not only for loop , Can also be next() Function calls continuously and returns the next value , Until the last throw StopIteration An error indicates that the next value cannot be returned .
Can be next() The object that function calls and returns the next value continuously is called an iterator :Iterator.
have access to isinstance() Determine whether an object is Iterator object ,list、dict、str Although it is Iterable, But not Iterator.
hold list、dict、str etc. Iterable become Iterator have access to iter() function :
isinstance(iter('abc'), Iterator)
The result is :True
Iterator It can even represent an infinite data flow , For example, all natural numbers . While using list It's never possible to store all natural numbers .
What works for The objects of the loop are all Iterable type ; What works next() Function objects are Iterator type , They represent a sequence of lazy calculations ; The collection data type is as follows list、dict、str Is such as Iterable, But it's not Iterator, But it can go through iter() Function to get a Iterator object .