美文网首页
循环控制: for循环2

循环控制: for循环2

作者: 闲云野鹤_23dd | 来源:发表于2021-01-07 18:53 被阅读0次

    使用for循环遍历 list

    使用for循环,将list 中的每个元素都操作一遍

    遍历 list

    def for_list():

    blist = ['哈', '楼', 'wo', 'de', 1, 2, 3]
    # 方式1, i代表列表中的每个元素
    for i in blist:
        print(i)
    
    # 方式2
    for i in range(len(blist)):
        print(f"循环第{i}次")
        print(blist[i])` 
    

    list去重

    def distenct():
        # list去重
        alist = [3, 2, 1, 5, 4, 4,5]
        blist= []
        for i in alist:
            if i not in blist:
                blist.append(i)
         print(blist)
    
    # 去重方式 2
    s = set(alist)
    print(s)` 
    

    嵌套循环

    def for_demo1():
        for i in range(5):
            print(f"外循环第{i}次")
            for j in range(3):
              print(f"    内循环第{j}次")` 
    

    list 转 字典 , 索引作为key , 索引对应的值 作为 value

    # list 转 字典 , 索引作为key , 索引对应的值 作为 value
    def list2dict():
      alist = [3, 2, 1, 5, 4, 4, 5]
    adict={}
    for i in range(len(alist)):
        v = alist[i]
        adict[i] = v
    print(adict)`
    

    练习:

    有两个列表:

    alist = ['哈', '楼', 4, 5, 1, 2, 3]
    blist = ['哈', '楼', 'wo', 'de', 1, 2, 3]
    请使用for循环遍历列表的方式 求出两个列表的 交集(两个列表都包含的元素) 和 差集(alist中有的元素blist中没有 和 blist中有的元素alist中没有 的元素)

    def list_for():
    alist = ['哈', '楼', 4, 5, 1, 2, 3]
    blist = ['哈', '楼', 'wo', 'de', 1, 2, 3]

    jiao = []
    cha = []
    for i in alist:
        if i in blist:
            jiao.append(i)
        else:
            cha.append(i)
    for j in blist:
        if j not in alist:
            cha.append(j)
    
    print(f"交集:{jiao}")
    print(f"差集:{cha}")
    

    相关文章

      网友评论

          本文标题:循环控制: for循环2

          本文链接:https://www.haomeiwen.com/subject/lnrdnktx.html