Home > Article > Backend Development > A brief introduction to iteration in Python (with code)
This article brings you a brief introduction to iteration in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
iter(): Convert a sequence into an iterator
next(): Automatically call the object The __next__()
method to iterate the object
map(): takes a sequence value as a parameter, calls a function in sequence, and returns the list directly in python2, but Returns an iterator in python3
# map经常配合lambdas来使用 items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items)) # 用于循环调用一列表的函数 def multiply(x): return (x*x) def add(x): return (x+x) funcs = [multiply, add] for i in range(5): value = map(lambda x: x(i), funcs) print(list(value)) # Output: # [0, 0] # [1, 2] # [4, 4] # [9, 6] # [16, 8]
filter(): Filters the elements in the list and returns a list consisting of all elements that meet the requirements, in A list is returned directly in python2, but an iterator is returned in python3
number_list = range(-5, 5) less_than_zero = filter(lambda x: x < 0, number_list) print(list(less_than_zero)) # Output: [-5, -4, -3, -2, -1]
# 配置从哪个数字开始枚举 my_list = ['apple', 'banana', 'grapes', 'pear'] for c, value in enumerate(my_list, 1): print(c, value) # 输出: (1, 'apple') (2, 'banana') (3, 'grapes') (4, 'pear')
The for loop in Python also has an else clause. This else clause will be executed when the loop ends normally, so it can often be used with break to use.
for item in container: if search_something(item): # Found it! process(item) break else: # Didn't find anything.. not_found_in_container()Object introspection
from functools import reduce product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] ) # Output: 24
The above is the detailed content of A brief introduction to iteration in Python (with code). For more information, please follow other related articles on the PHP Chinese website!