遍历Python中的列表 [英] Looping over a list in Python
问题描述
我有一个带有子列表的列表.我想打印所有长度等于3的子列表.
I have a list with sublists in it. I want to print all the sublists with length equal to 3.
我正在python中执行以下操作:
I am doing the following in python:
for x in values[:]:
if len(x) == 3:
print(x)
values
是原始列表.上面的代码是否为每个x
值打印每个长度等于3的子列表?我只想显示一次length == 3
的子列表.
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.
问题已解决.问题出在Eclipse编辑器上.我不明白原因,但是当我运行循环时,它只显示列表的一半.
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.
我在Eclipse中需要更改任何设置吗?
Are there any settings I have to change in Eclipse?
推荐答案
尝试一下,
x in mylist
比x in mylist[:]
更好并且更具可读性,并且len(x)
应该等于3
.
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]
或者如果您需要更多的Python语言,请使用列表理解
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屋!