How list of lists iteration is working in python?

后端 未结 2 1361
無奈伤痛
無奈伤痛 2021-01-07 07:41

I have a list of list like this:-

lst = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]

If I run these I got output like these.I am not gettin

相关标签:
2条回答
  • 2021-01-07 08:18
    [j for i in list for j in i]
    

    This is similar to

    result = []
    for i in list:
        for j in i:
            result.append(j)
    

    In general the list comprehension like [p for a in b if c == d for e in f if etc] will be translated to like

    reuslt = []
    for a in b: if c == d: for e in f: if etc: result.append(p)
    

    [j for j in i for i in list]
    

    Normally this won't even run. Probably you have defined i to be [8, 9] previously.

    >>> [j for j in i for i in list]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'i' is not defined
    

    This is equivalent to

    result = []
    for j in i: 
        for i in list:
            result.append(j)
    

    so if i is not defined at first, the loop will not work.

    0 讨论(0)
  • 2021-01-07 08:22

    At the end of first LC i is assigned to [8,9]:

    >>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
    >>> [j for i in lis for j in i]
    [1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
    >>> i
    [8, 9]
    

    Now in the second LC you're iterating over this i:

    >>> [j for j in i for i in lis]
    [8, 8, 8, 8, 9, 9, 9, 9]
    

    Both LC's are (roughly)equivalent to:

    >>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
    >>> for i in lis:
    ...     for j in i:
    ...         print j,
    ...         
    1 2 3 4 5 6 4 5 6 7 8 9
    >>> i
    [8, 9]
    >>> for j in i:
    ...     for i in lis:
    ...         print j,
    ...         
    8 8 8 8 9 9 9 9
    

    This has been fixed in py3.x:

    in particular the loop control variables are no longer leaked into the surrounding scope.

    Demo(py 3.x):

    >>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
    >>> [j for i in lis for j in i]
    [1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
    >>> i
    Traceback (most recent call last):
    NameError: name 'i' is not defined
    
    >>> j
    Traceback (most recent call last):
    NameError: name 'j' is not defined
    
    0 讨论(0)
提交回复
热议问题