• python zip函数



    使用zip()函数来可以把列表合并,并创建一个元组对的列表

    我语言表达起来可能有些粗糙,话不多说看示例

    #示例1

    l1=[1,2,3]
    lt2=[4,5,6]
    lt3=zip(l1,lt2)
    #zip()是可迭代对象,使用时必须将其包含在一个list中,方便一次性显示出所有结果
    #print(lt3)
    #print(list(lt3))
    #print(dict(lt3))
    lt4=['dd','18','183']
    lt5=['name','age','height']
    a=zip(lt5,lt4)
    print(dict(a))

    #zip()参数可以接受任何类型的序列,同时也可以有两个以上的参数;
    # 当传入参数的长度不同时,zip能自动以最短序列长度为准进行截取

    l1, l2, l3 = (1, 2, 3), (4, 5, 6), (7, 8, 9)
    print(list(zip(l1, l2, l3)))
    
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    
    str1 = 'abc'
    str2 = 'def123'
    print(list(zip(str1, str2)))
    
    [('a', 'd'), ('b', 'e'), ('c', 'f')]

    ##一个坑
    ###坑1

    l1 = [1, 2, 3, 4]
    l2 = [2, 3, 4, 5]
    l3 = zip(l1, l2)
    
    for i in l3:
    print('for循环{}'.format(i))
    
    l4 = [x for x in l3]
    print(l4)

    #坑2

    l1 = [1, 2, 3, 4]
    l2 = [2, 3, 4, 5]
    l3 = zip(l1, l2)
    
    l4 = [x for x in l3]
    print(l4)
    
    for i in l3:
    print('for循环{}'.format(i))


    ###for循环没执行!!!,咋整的,查下zip看一下


    ##Return a zip object whose .__next__() method returns a tuple where
    # the i-th element comes from the i-th iterable argument. The .__next__()
    # method continues until the shortest iterable in the argument sequence
    # is exhausted and then it raises StopIteration.

    # 返回一个zip对象,其中.__next__()方法返回一个元组
    # 第i个元素来自第i个可迭代参数。.__next__()
    # 方法继续执行,直到参数序列中最短的可迭代
    # 耗尽,然后引发StopIteration。

    #重点就是这个 “zip对象” 是一个迭代器。 迭代器只能前进,不能后退
    #它空了,所以没有执行,空的东西怎么遍历

  • 相关阅读:
    第十二章类的无参方法
    第十三章人机猜拳
    第十一章类和对象
    面向对象七大原则。
    深入类的方法。
    使用集合组织相关数据。
    .NET框架
    C#数据类型
    错误。
    实现Windows的数据绑定
  • 原文地址:https://www.cnblogs.com/wdz1226/p/10181354.html
Copyright © 2020-2023  润新知