Python built-in functions (enumerate, map, zip, filter)

enumerate() function

  • The enumerate() function is the meaning of enumeration

  • Format: enumerate(argument, start=0)

  • argument can be an iterator or an iterable (list/string/tuple...)

  • start is the index value returned by default, starting from 0 by default and can be modified

  • Usually used with a for loop, you can get the index and value of the traversed object, one-to-one correspondence

# 1. Use with strings
str1 = 'python'
for index,value in enumerate(str1):
    print(f'{index}:{value}')
# result
0:p
1:y
2:t
3:h
4:o
5:n
# 2. Use with lists (same as tuples)
l = ['Hammer','jason','tony']
for a,b in enumerate(l):
    print(f'{a},{b}')
# result
0,Hammer
1,jason
2,tony

#3. Use with a collection
s = {"aline","Hammer",18,'199****1234'}
for index,value in enumerate(s):
    print(f'{index},{value}')
# result
0,Hammer
1,aline
2,18
3,199****1234

# 4. Use with a dictionary
dic = {'name':'hammer','age':18,'number':'199***1234'}
for index,value in enumerate(dic):
    # This is the key that directly outputs the dictionary
    print(f'{index}:{value}')
# result
0:name
1:age
2:number
for index, value in enumerate(dic):
    # Output the value of the dictionary
    print(f'{index}:{dic[value]}')
# result
0:hammer
1:18
2:199***1234

Note that enumeration is used for dictionaries and collections, and the position of the index may not correspond to the values ​​​​of dictionaries and collections in order, because of the disorder of dictionaries and collections!

# collection example
s={'one','two','three','four'}
for index,value in enumerate(s,start=1):
    print(f'{index}:{value}')
# As a result, there is no correspondence between 1 and one, because of the unordered nature of the set

1:three
2:four
3:two
4:one
  • The default output start position is 0, you can modify the default start position

  • eg: start = 0 >>>> start = 1 / write 1 directly

lst = ['HammerZe','jason','tony']
# The starting position defaults to 0
for index,value in enumerate(lst):
    print(f'{index}:{value}')
#Modify the default position to 1, write start = 1 / write 1 directly

for index,value in enumerate(lst,start=1):
    print(f'{index}:{value}')
# As a result, write a piece
0:HammerZe
1:jason
2:tony


1:HammerZe
2:jason
3:tony

map() function

  • The map() function means mapping, and the specified sequence is mapped according to the provided function

  • Format: map(function,iterable) # iterable: iterable object

  • The first parameter is the function name, and the second parameter is an iterable object

  • Process: Loop through each element in the iterable object and pass it to the function function, save the return value, return a new iterable object, and iterable object without modification principle.

# The use of the map function, used with the lambda function
'''Case 1''': 
# define an iterable object
lst = [1,2,3,4,5]
# Use res to receive the return value of the map function and convert it into a list
# lambda function function: add 2 to each element in the lst list
res = list(map(lambda x:x+2,lst))
print(res)
# result
[3, 4, 5, 6, 7]

'''Case 2'''
# Interview questions (hint: use map function, lambda function, list comprehension)
# One line of code implementation, find the sum of squares of even numbers within 10
print(sum(map(lambda x: x ** 2, [x for x in range(1, 10) if x % 2 == 0])))

#Step by step
# 1. Traverse the even numbers from 1 to 10
even_num = [x for x in range(1,10) if x % 2 ==0] #[2, 4, 6, 8]
# 2. To square each element, use the mapping and lambda calculation formulas
# print(even_num)
square_num = map(lambda x:x**2,even_num) # [4, 16, 36, 64]
#print(list(square_num))
# 3. Final summation
print(sum(square_num))

# two results
120

zip() function

  • The zip() function obtains elements from one or more iterators, combines them into a new iterator, and returns them in the form of a list set of tuples.

  • If the lengths of the iterator objects passed in the zip() function are not equal, the iterator with the shortest length is used as the benchmark.

  • If you really don't understand, you can think of the function as a "zipper", a zipper is generally long, or think about the short board effect

  • Format:

  • zip(iterable1,iterable2···iterablen)

  • iterable is an iterable object

l = [1,2,3,4]
# The zip() function passes in a parameter
get_return = list(zip(l))
print(get_return)

# The zip() function passes in two arguments of equal length (a list and a tuple)
# As long as the iterable objects are of different types
l1 = [1,2,3,4]
l2 = ('HammerZe',18,'male','study')
get_return = list(zip(l1,l2))
print(get_return)

# The zip() function passes in multiple parameters of unequal length
l1 = [1,2,3,4]
l2 = ['HammerZe',18,'male','study']
l3 = ['name','age','gender','hobby','number','height']
get_return = list(zip(l1,l2,l3))
print(get_return)  # Only 4 elements of l3 are output, taking the shortest list as a reference

# Three example results:
[(1,), (2,), (3,), (4,)]
[(1, 'HammerZe'), (2, 18), (3, 'male'), (4, 'study')]
[(1, 'HammerZe', 'name'), (2, 18, 'age'), (3, 'male', 'gender'), (4, 'study', 'hobby')]

filter() function

  • The filter() function is used to filter the elements in the iterable object, filter out the unqualified elements, and return the qualified elements to form a new list.

  • Format:

  • filter(function , iterable)

  • function is the function name, iterable is an iterable object

# Output odd numbers within 1-10
l = [1,2,3,4,5,6,7,8,9,10]
res = filter(lambda x:x%2==1,l)
print(list(res))
#result

[1, 3, 5, 7, 9]

Tags: Python zip map

Posted by bschmitt78 on Sun, 26 Mar 2023 09:17:19 +1030