This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .
When you use for Loop through , You need to use two parameters :
enumerate Function returns a generator object , This object supports iterative protocols , After that, I will discuss in my blog . This means that after the function is called , Will return a tuple (index,value).
S = [‘a’,‘b’,‘c’]
for (i,value) in enumerate(S):
print(i, 'and', value)
>>>
0 and a
1 and b
2 and c
Use enumerate Function can get the element and its subscript at the same time , Some code operations are omitted , It's more convenient .
python The built-in zip The function allows us to use for To traverse multiple sequences . for example :
L1 = [1,2,3,4]
L2 = [5,6,7,8]
lis = list(zip(L1,L2))
print(lis)
>>>[(1,5),(2,6),(3,7),(4,8)]
for (x,y) in zip(L1,L2):
print(x,y,"=",x+y)
>>>
1 5 = 6
2 6 = 8
3 7 = 10
...
...
...
The above example 1 in ,zip Create tuple pairs and store them in the list . example 2 Use in for Go through the epochs and make pairs . That is to say, it scans in the loop L1 and L2. Here we have a preliminary understanding of zip function . Let's take a closer look at zip:
L1 = [1,2,3,4]
L2 = [5,6,7,8]
L3 = [4,3,2,1]
list(zip(L1,L2,L3))
>>>[(1,5,4),(2,6,3),(3,7,2),(4,8,1)]
L1 = [a,b,c]
L2 = [1,2,3,4]
list(zip(L1,L2))
>>>[(a,1),(b.2),(c,3)]
keys = ['name','age','job']
vals = ['ww',23,'student']
d = dict(zip(keys,vals))
>>>{'name' : 'ww', 'age' : 23, 'job' : 'student'}
python One of the functions of a set in is to remove duplicate elements from a string or list . This function is very useful . such as :
Output is :
It's not enough just to know , There are several features to note when using set de duplication . Let's look at the above code , It was found that the order of the elements in the list changed after the list was changed to a set , in the majority of cases , We all want the order of sets to be the same as that of lists . So readers can read another blog post link : python How to remove duplicate elements in .
In addition, the author found that , When performing set conversion on numbers , The order of the numbers is automatically sorted . Please have a look at :
Output is :
So we come to :