在 Python 中循环遍历列表 [英] Looping over a list in Python
问题描述
我有一个包含子列表的列表.我想打印长度等于 3 的所有子列表.
我在 python 中执行以下操作:
for x in values[:]:如果 len(x) == 3:打印(x)
values
是原始列表.上面的代码是否为 x
的每个值打印每个长度等于 3 的子列表?我想只显示 length == 3
一次的子列表.
问题解决了.问题出在 Eclipse 编辑器上.我不明白原因,但是当我运行循环时它只显示我列表的一半.
我需要在 Eclipse 中更改任何设置吗?
x in mylist
比 x in mylist[:]
和你的 更好,更易读>len(x)
应该等于 3
.
或者如果您需要更多 Pythonic 使用 list-comprehensions
<预><代码>>>>[x for x in mylist if len(x)==3][[1, 2, 3], [8, 9, 10]]>>>I have a list with sublists in it. I want to print all the sublists with length equal to 3.
I am doing the following in python:
for x in values[:]:
if len(x) == 3:
print(x)
values
is the original list. Does the above code print every sublist with length equal to 3 for each value of x
? I want to display the sublists where length == 3
only once.
The problem is solved. The problem is with the Eclipse editor. I don't understand the reason, but it is displaying only half of my list when I run my loop.
Are there any settings I have to change in Eclipse?
x in mylist
is better and more readable than x in mylist[:]
and your len(x)
should be equal to 3
.
>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
or if you need more pythonic use list-comprehensions
>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
这篇关于在 Python 中循环遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!