python [iter(list)] * 2是什么意思?

发布于 2021-01-29 15:05:32

我在网络中找到了下面的代码,结果是列表中两个元素的元组,如何理解[iter(list)]*2

lst = [1,2,3,4,5,6,7,8]
b=zip(*[iter(lst)]*2)
list(b)

[(1, 2), (3, 4), (5, 6), (7, 8)]

------------
[iter(lst)]*2
[<list_iterator at 0x1aff33917f0>, <list_iterator at 0x1aff33917f0>]

[iter(lst)]*2在上面检查了相同的迭代器,因此意味着iter重复两次,因此,如果我从2到3检查num,结果应该是[(1, 2, 3), (4, 5, 6),(7,8,NaN)] 但删除7,8

lst = [1,2,3,4,5,6,7,8]
b=zip(*[iter(lst)]*3)
list(b)
--------------
[(1, 2, 3), (4, 5, 6)]
关注者
0
被浏览
131
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    解释起来很棘手。我会试一试:

    [iter(lst)]您创建一个包含一个项目的列表。该项目是列表上的迭代器。

    每当python尝试从此迭代器获取元素时,lst都会返回的下一个元素,直到没有更多元素可用为止。

    只需尝试以下操作:

    i = iter(lst)
    next(i)
    next(i)
    

    输出应如下所示:

    >>> lst = [1,2,3,4,5,6,7,8]  
    >>> i = iter(lst)
    >>> next(i)
    1
    >>> next(i)
    2
    >>> next(i)
    3
    >>> next(i)
    4
    >>> next(i)
    5
    >>> next(i)
    6
    >>> next(i)
    7
    >>> next(i)
    8
    >>> next(i)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    

    现在,您将创建一个包含两次 完全相同的 迭代器的列表。你这样做 itlst = [iter(lst)] * 2

    试试以下:

    itlst1 = [iter(lst)] * 2
    itlst2 = [iter(lst), iter(lst)]
    print(itlst1)
    print(itlst2)
    

    结果将类似于:

    >>> itlst1 = [iter(lst)] * 2
    >>> itlst2 = [iter(lst), iter(lst)]
    >>> print(itlst1)
    [<list_iterator object at 0x7f9251172b00>, <list_iterator object at 0x7f9251172b00>]
    >>> print(itlst2)
    [<list_iterator object at 0x7f9251172b70>, <list_iterator object at 0x7f9251172ba8>]
    

    需要注意的重要一点是,该itlst1列表包含两次相同的迭代器,而itlst2包含两个不同的迭代器。

    说明尝试输入:

    next(itlst1[0])
    next(itlst1[1])
    next(itlst1[0])
    next(itlst1[1])
    

    并将其与:

    next(itlst2[0])
    next(itlst2[1])
    next(itlst2[0])
    next(itlst2[1])
    

    结果是:

    >>> next(itlst1[0])
    1
    >>> next(itlst1[1])
    2
    >>> next(itlst1[0])
    3
    >>> next(itlst1[1])
    4
    >>> 
    >>> next(itlst2[0])
    1
    >>> next(itlst2[1])
    1
    >>> next(itlst2[0])
    2
    >>> next(itlst2[1])
    2
    

    现在到zip()函数(https://docs.python.org/3/library/functions.html#zip):

    请尝试以下操作:

    i = iter(lst)
    list(zip(i, i))
    

    zip()有两个参数。每当您尝试从中获取下一个元素时,zip都将执行以下操作:

    • 从作为第一个参数的iterable中获得一个值
    • 从iterable中获取一个值,该值是第二个参数
    • 返回具有这两个值的元组。

    list(zip(xxx)) 将重复执行此操作并将结果存储在列表中。

    结果将是:

    >>> i = iter(lst)
    >>> list(zip(i, i))
    [(1, 2), (3, 4), (5, 6), (7, 8)]
    

    下一个使用的技巧是用于*将第一个元素用作函数调用的第一个参数,将第二个元素用作第二个参数,依此类推)*(双星号/星号)和(星号/星号)的作用是什么做参数?

    所以写:

    itlst1 = [iter(lst)] * 2
    list(zip(*itlst1))
    

    在这种情况下等于

    i = iter(lst)
    itlst1 = [i] * 2
    list(zip(itlst1[0], itlst[1]))
    

    等同于

    list(zip(i, i))
    

    我已经解释过了

    希望以上解释了大多数技巧。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看