Explanation of Python Built in Function zip map filter

  • 2021-10-16 02:14:31
  • OfStack

Parallel traversal of zip

zip takes one or more sequences as parameters and returns a list of tuples pairing side-by-side elements in these sequences.


L1=[1,2,3,4]
L2=[5,6,7,8]
L3=zip(L1,L2)
print(L3,type(L3))

<zip object at 0x7feb81b17f08> <class 'zip'>

zip is an iterable object in python3, and we can include it in an list call to show all results once


list(L3)

[(1, 5), (2, 6), (3, 7), (4, 8)]

Use with for loop to run parallel iterations


for (x,y) in zip(L1,L2):
  print(x,y,'--',x+y)

1 5 -- 6
2 6 -- 8
3 7 -- 10
4 8 -- 12

Constructing a dictionary using zip


keys=['spam','eggs','toast']
val=[1,3,5]

The elements in the keys and val lists are concatenated through zip, and the zip key/value list is passed to the built-in dict constructor


D3=dict(zip(keys,val))
print(D3)

{'spam': 1, 'eggs': 3, 'toast': 5}

map

Traverse the sequence, manipulate each element in the sequence, and finally get a new sequence in the format: map (func, list)
Apply each element in list to the function func


map_obj=map(abs,(-10,0,9))
print(list(map_obj))

<zip object at 0x7feb81b17f08> <class 'zip'>
0

filter

The elements in the sequence are screened, and finally the qualified sequence is obtained, which is often used with lambda function 1 and format filter (func, list)
The elements in list are applied to func in turn, and the elements that meet the conditions are returned


<zip object at 0x7feb81b17f08> <class 'zip'>
1

<zip object at 0x7feb81b17f08> <class 'zip'>
2

Related articles: