zoukankan      html  css  js  c++  java
  • python zip()

    >>> help(zip)
    Help on built-in function zip in module __builtin__:
    
    zip(...)
        zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
        
        Return a list of tuples, where each tuple contains the i-th element
        from each of the argument sequences.  The returned list is truncated
        in length to the length of the shortest argument sequence.
    
    >>> list_1 = ['name', 'age']
    >>> list_2 = ['wang', 23]
    >>> zip(list_1, list_2)
    [('name', 'wang'), ('age', 23)]
    >>> dict(zip(list_1, list_2))
    {'age': 23, 'name': 'wang'}
    

    如果两个参数不一样长,那么取短的。  

    也可以反向操作,见下面:

    >>> list_3
    {'age': 23, 'name': 'wang'}
    >>> list_1 = ['name', 'age']
    >>> list_2 = ['wang', 23]
    >>> list_3 = zip(list_1, list_2)
    >>> list_3
    [('name', 'wang'), ('age', 23)]
    >>> l1, l2 = zip(*list_3)
    >>> list_1 == list(l1)
    True
    >>> type(l1)
    <type 'tuple'>
    >>> list_2 == l2
    False
    >>> list_2 == list(l2)
    True
    

     

     自然,也可以操作三个或者一个参数:

    >>> zip(list_1)
    [('name',), ('age',)]
    >>> zip(list_1, list_2, l1)
    [('name', 'wang', 'name'), ('age', 23, 'age')]
    

      

    python.org的解释:

    1. This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

    2. The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

    3.zip() in conjunction with the * operator can be used to unzip a list

  • 相关阅读:
    书籍下载点
    总结一下散乱的开发点滴(3) (高手勿入)
    [收藏]Dynamic Controls in ASP.NET
    [收藏] ORACLE中函数
    面试题收集,面试和被面试中煎熬~~
    一句SQL得出表中重复的数据(TMP)
    总结一下散乱的开发点滴(4) (高手勿入)
    一个同步的例子
    关于学习的反思(下)系网开发记(4)
    关于学习的反思(上)系网开发记(2)
  • 原文地址:https://www.cnblogs.com/wswang/p/5555716.html
Copyright © 2011-2022 走看看