• 【列表推导式-以及练习题】



    通过一行循环判断,遍历出一系列数据的方式是推导式
    语法: val for val in Iterable (把想要的值写在 for的左侧)
    里面是一行循环判断!根据套在推导式外层的符号判断具体是什么类型的推导式

    推导式种类三种:
    [val for val in Iterable] 列表推导式
    {val for val in Iterable} 集合推导式
    {a:b for a,b in iterable} 字典推导式

    lst=[1,2,3,4,5,3]
    lst_new=[]
    for i in range(1,51):
    lst_new.append(i)
    print(lst)

    print(lst_new)
    #基本写法
    lst=[i for i in range(2,44)]
    print(lst)
    #普通推导式
    lst=[1,24,2]
    lst_new=[]
    for i in lst:
    if i %2==0:
    lst_new.append(i)
    print(lst_new)
    lst1=[i for i in lst if i%2==0]
    print(lst1)
    #关于推导式的练习


    #(1).{'x': 'A', 'y': 'B', 'z': 'C' } 把字典写成x=A,y=B,z=C的列表推导式
    dic={"x":"A","y":"B","z":"C"}
    lst=[]
    # for k,v in dic.items():
    # # print(k,v)
    # res=k+"="+v
    # lst.append(res)
    # print(lst)

    lst=[k+"="+v for k,v in dic.items()]
    print(lst)
    # (2).把列表中所有字符变成小写 ["ADDD","dddDD","DDaa","sss"]
    lst=["ADDD","dddDD","DDaa","sss"]
    # lst_new=[]
    # for i in lst:
    # res=i.lower()
    # lst_new.append(res)
    # print(lst_new)

    lst=[i.lower() for i in lst]
    print(lst)

    # (3).x是0-5之间的偶数,y是0-5之间的奇数 把x,y组成一起变成元组,放到列表当中
    lst=[]
    # for i in range(0,6):
    # for j in range(0,6):
    # if i%2==0 and j%2==1:
    # res=i,j
    # lst.append(res)
    # print(lst)
    lst = [ (x,y) for x in range(6) if x % 2 == 0 for y in range(6) if y % 2 == 1 ]
    print(lst)

    # (4).使用列表推导式 制作所有99乘法表中的运算
    print("==============")
    # for i in range(1,10):
    # for j in range(1,i+1):
    # #:d 整数占位符,可以写也可以不写
    # print("{:d}*{:d}={:2d}".format(i,j,i*j),end=" ")
    # print()
    lst=["{:d}*{:d}={:2d}".format(i,j,i*j) for i in range(1, 10) for j in range(1,i+1)]
    print(lst)

    # (5)#求M,N中矩阵和元素的乘积
    # M = [ [1,2,3],
    # [4,5,6],
    # [7,8,9] ]

    # N = [ [2,2,2],
    # [3,3,3],
    # [4,4,4] ]
    # =>实现效果1 [2, 4, 6, 12, 15, 18, 28, 32, 36]
    # =>实现效果2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]]
    M=[ [1,2,3],[4,5,6],[7,8,9] ]
    N=[ [2,2,2],[3,3,3],[4,4,4] ]
    #控制下标就等于控制了最后的结果
    """
    M[0][0] * N[0][0] = 2
    M[0][1] * N[0][1] = 4
    M[0][2] * N[0][2] = 6

    M[1][0] * N[1][0] = 12
    M[1][1] * N[1][1] = 15
    M[1][2] * N[1][2] = 18

    M[2][0] * N[2][0] = 28
    M[2][1] * N[2][1] = 32
    M[2][2] * N[2][2] = 36"""

    # lst=[M[i][j]*N[i][j] for i in range(0,3) for j in range(0,3)]
    # print(lst)

    # 第二个效果
    # [ [] , [] , [] ] 通过推导式遍历出三个新列表
    lst=[[i] for i in range(3)]
    print(lst)

    """
    外层i动的慢的,里层的j动的快的,所以下标M[i][j]
    在拿出i的时候, 里面的for 循环了三遍 是在一个新的列表当中实现的;
    """
    lst=[[M[i][j]*N[i][j] for j in range(3)]for i in range(3)]
    print(lst)
  • 相关阅读:
    linux下安装nginx
    阿里云CentOS系统配置iptables防火墙
    没用私服,自己安装下本地jar包,制作坐标
    Redis加入Centos Linux开机启动
    CentOS6.5安装redis(3.0.3)
    Spring Boot 第一个demo
    JDK下载与安装
    IDEA-Maven下载及安装
    项目注意:
    idea项目Tomcat 插件 运行报错
  • 原文地址:https://www.cnblogs.com/bonnyxinxin/p/13055408.html
Copyright © 2020-2023  润新知