美文网首页
python中zipped用法

python中zipped用法

作者: 慧琴如翌 | 来源:发表于2018-04-21 15:09 被阅读230次

    zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
    注意:1. 入参是可迭代的对象;2. 将可迭代对象中的对应元素打包成一个个元祖;3. 结果是一个列表;4.迭代器中的元素个数不一致时,以最少个数的为准;5.利用 * 号操作符,可以将元组解压为列表

    # zip的用法
    def zip1():
        a = [1,2,3]
        b = [4,5,6]
        zipped = zip(a,b)
        print zipped    #[(1, 4), (2, 5), (3, 6)]
        c = (1,2,3)
        d = (4,5,6)
        zipped2 = zip(c,d)
        print zipped2  #[(1, 4), (2, 5), (3, 6)]
    
    # zip的结果可以作为入参生成字典
    def zip2():
        a = [1,2,3]
        b = [4,5,6]
        zipped = zip(a,b)    # [(1, 4), (2, 5), (3, 6)]
        dict1 = dict(zipped)  # {1: 4, 2: 5, 3: 6}
        print dict1
    zip2()
    
    
    
    In [27]: a = [1,2,3]
    
    In [28]: b = [4,5,6]
    
    In [29]: zipped = zip(a,b)
    
    In [30]: zipped
    
    Out[30]: [(1, 4), (2, 5), (3, 6)]
    
    In [31]: r1 = zip(*zipped)
    
    In [32]: r1
    
    Out[32]: [(1, 2, 3), (4, 5, 6)]
    
    In [33]: 
    
    

    相关文章

      网友评论

          本文标题:python中zipped用法

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