• python:列表生成式的学习


    看个例子:

    # 定义一个列表
    l=[1,2,3,4,5]
    #()用于创建一个list,结果依次返回列表l的元素的平方,返回list
    s=[i*i for i in l]
    # 打印列表s
    print(s)
    # ()用于创建一个生成器,结果依次返回列表l的元素的平方,返回generator
    s1=(i*i for i in l)
    # 以列表形式打印generator的元素值
    print(list(s1))
    # 查看s1的类型
    print(type(s1))

    输出:

    [1, 4, 9, 16, 25]
    [1, 4, 9, 16, 25]
    <class 'generator'>

    1、列表生成式即List Comprehensions,如何生成列表:

    a=list(range(1,11))
    print(a)
    print(type(a))

    输出:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    <class 'list'>

    2、如果要生成一个[1*1,2*2,......,10*10]的列表:

    a=[i*i for i in range(1,11)]
    print(a)

    输出:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    3、根据列表[1*1,2*2,......,10*10],帅选出偶数的平方的一个列表:

    a=[i*i for i in range(1,11) if i%2==0]
    print(a)

    输出:[4, 16, 36, 64, 100]

    4、使用两层循环,可以生成全排列

    a=[m+n for m in "xyz" for n in "ABC"]
    print(a)

    输出:['xA', 'xB', 'xC', 'yA', 'yB', 'yC', 'zA', 'zB', 'zC']

    三层循环很少用到

    5、for循环迭代一个dict,dict的items可以同时迭代key和value,使用两个变量生成一个list:

    a={'a':'A','b':'B','c':'C'}
    b=[key +'='+value for key,value in a.items()]
    print(b)

    输出:['a=A', 'b=B', 'c=C']

    6、把一个list所有的字母变成小写:

    a={'Abc','Hello','APPLE'}
    b=[i.lower() for i in a]
    print(b)

    输出:['apple', 'abc', 'hello']

    假如list中含有数字则会报错:AttributeError: 'int' object has no attribute 'lower'

    a={'Abc','Hello','APPLE',18}
    b=[i.lower() for i in a if type(i)==str]
    print(b)

    输出:['abc', 'hello', 'apple']

    业精于勤而荒于嬉,勤劳一日,可得一日安眠;勤劳一生,可得幸福一生。因为,我们努力了;因为,天道酬勤。
  • 相关阅读:
    COGS 859. 数列
    9.7noip模拟试题
    hash练习
    9.6noip模拟试题
    9.5noip模拟试题
    poj 2117 Electricity
    洛谷P1993 小 K 的农场(查分约束)
    9.2noip模拟试题
    洛谷 P1273 有线电视网(dp)
    面试题收集
  • 原文地址:https://www.cnblogs.com/Mr-choa/p/12634223.html
Copyright © 2020-2023  润新知