列表迭代列表如何在python中工作? [英] How list of lists iteration is working in python?

查看:67
本文介绍了列表迭代列表如何在python中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表清单:-

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 getting how these are working.

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

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

任何人都可以解释一下它们是如何给出输出的.这两次迭代之间有什么区别?

Can anyone please explain how those are giving output like this.what is the differnt between this two iteration?

推荐答案

在第一个LC的结尾将i分配给[8,9]:

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]

现在在第二个LC中,您要遍历此i:

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]

两个LC都(大致)等同于:

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


此问题已在py3.x中修复 > :


This has been fixed in py3.x:

尤其是循环控制变量不再泄漏到 范围.

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

演示(py 3.x):

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

这篇关于列表迭代列表如何在python中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆