Home  >  Article  >  Backend Development  >  A brief introduction to iteration in Python (with code)

A brief introduction to iteration in Python (with code)

不言
不言forward
2018-09-28 14:24:381934browse

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.

Iteration related

  • 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]
  • ##enumerate(): iterates through the data and counts automatically, and has many useful optional parameters

  • # 配置从哪个数字开始枚举
    my_list = [&#39;apple&#39;, &#39;banana&#39;, &#39;grapes&#39;, &#39;pear&#39;]
    for c, value in enumerate(my_list, 1):
        print(c, value)
    
    # 输出:
    (1, &#39;apple&#39;)
    (2, &#39;banana&#39;)
    (3, &#39;grapes&#39;)
    (4, &#39;pear&#39;)
  • for-else

    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&#39;t find anything..
        not_found_in_container()
Object introspection

  • dir(): Returns a list of properties and methods owned by an object. If not passed Enter the parameters, then it will return all the names in the current scope

  • type(): Return the type of an object

  • id(): Returns the unique ID of any different kind of object Reduce is a very useful function when calculating and returning results.

  • 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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete