day13 ternary expressions with, list formula, generator expression, anonymous function, built-in functions

A triplet of expressions:

  • grammar:

    Condition holds return value if left to determine the conditions else condition does not hold the right of return value

    # 需求: 让用户输入用户名,输入的用户如果不是tank,为其后缀添加_DSB
    username = input('请输入用户名:').strip()
    new_username = username if username == 'tank' else username + '_DSB'
    print(new_username)

List of formula:

  • You can generate a list of his party achieved.

  • grammar:

    list = [a value taken for each, for each arbitrary value of an object may be taken out in an iterative iterables]

    It is right for the number of cycles, and may be taken out of each value iterables

    for the left can add value to the current list

    list = [a value for each iteration may be withdrawn in the object iterable]

    list = [value for each value of the iteration can be retrieved object if the object is determined in the iteration may be]

    # 列表生成式
    # 普通的
    new_list = []
    for i in range(1, 6):
        new_list.append(i)
    print(new_list)
    
    #列表
    new_list = [i for i in range(1, 6)]
    print(new_list)

Generator expressions (formula builder)

  • 1. What is a generator?
    Generation tools, the generator is a custom iterator, essentially iterators

  • If the function comprises the yield keyword, and then call the function, the code does not perform the function thereof, i.e., the return value obtained amount generator object.

  • List formula: If the data amount h using

    advantage:

    You can rely on index values

    Disadvantages:

    Waste of resources

  • Builder formula: If the large amount of data using

  • (Line for line in range (1, 6)) ---> g ​​generators (1, 2, 3, 4, 5)

    advantage:

    Save resources

    Disadvantages:

    The value is not convenient

    # 生成一个有1000个值的生成器
    g = (line for line in range(1, 1000001))
    # <generator object <genexpr> at 0x00000203262318E0>
    print(g)
    
    # 列表生成式实现
    list1 = [line for line in range(1, 1000001)]
    print(list1)
    

Anonymous function

  • No name function

    Parameter is left, the right is the return value

    lambda :
    PS: The reason, because there is no name, call the name of the function + ()
    Anonymous function requires a one-time use.
    Note: Anonymous functions using meaningless alone, it makes sense to be used in conjunction with "built-in function"

Built-in functions

  • Built-in methods provided inside python

    max , min , sorted , map , filter

    dict1 = {
        'tank': 1000,
        'egon': 500,
        'sean': 200,
        'jason': 500
    }
    print(max(dict1, key=lambda x:dict1[x]))  #max,最大。排序根据ASCII自码表排序的
    
    print(min(dict1,key=lambda x:dict1[x]))# 最小的
    
    new_list = sorted(dict1,key=lambda x: dict1[x],reverse=True)
    print(new_list)

Guess you like

Origin www.cnblogs.com/lishuangjian/p/11861948.html