• list, set, dict, generator comprehension


    list comprehension:

    my_list = [num*num for num in range(1,11)]
    print(my_list)

    if使用

    my_list = [num for num in range(1,11) if num > 5]
    print(my_list)

    if在for循环后面

    if else使用

    my_list = [num if num < 5 else 'larger' for num in range(1,11) ]
    print(my_list)

    if在for循环前面

    set comprehension与list comprehension类似,区别在于list使用的是[],而set得用()

    例如:

    my_list = [1,1,1,2,2,3,3,3,3,4,4,7,7,7,9,9,9,9]
    my_set = {num for num in my_list}
    print(my_set)

    结果为:

    {1, 2, 3, 4, 7, 9}

    dict comprehension:

    简单易懂的方法:

    names = ['peter', 'clark', 'wade', 'bruce', 'logan']
    heros = ['spideman', 'superman', 'deadpool', 'batman', 'wolverine']
    my_dict = {}
    for name, hero in zip(names, heros):
        my_dict[name] = hero
    print(my_dict)

    dict comp:

    names = ['peter', 'clark', 'wade', 'bruce', 'logan']
    heros = ['spideman', 'superman', 'deadpool', 'batman', 'wolverine']
    my_dict = {name: hero for name, hero in zip(names, heros)}
    print(my_dict)

    结果都是:

    {'peter': 'spideman', 'clark': 'superman', 'wade': 'deadpool', 'bruce': 'batman', 'logan': 'wolverine'}

    generator comprehension:

    注意:

    上面的list用的是[];

    dict用的是{}

    set用的也是{},区别是没有:

    而generator用的是()

    my_gen = (num for num in range(1,11))
    for item in my_gen:
        print(item)
  • 相关阅读:
    MFC单文档中进行plc点云显示
    modbus发送和接收
    测试左移和测试右移
    2021软件测试笔试题
    202106月份总结测试开发面试题
    KuaiShou面试题
    阿拉伯数学手写体。
    GeminiScrollbar
    vue-core-video-player
    webpack
  • 原文地址:https://www.cnblogs.com/profesor/p/12902903.html
Copyright © 2020-2023  润新知