Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - 遍历Python中的列表(Looping over a list in Python)

I have a list with sublists in it.

(我有一个带有子列表的列表。)

I want to print all the sublists with length equal to 3.

(我想打印长度等于3的所有子列表。)

I am doing the following in python:

(我在python中执行以下操作:)

for x in values[:]:
    if len(x)==3:
        print x

values is the original list.

(values是原始列表。)

Does the above code print all the sublist with length equal to 3 for each value of x ?

(上面的代码是否为x每个值打印所有长度等于3的子列表?)

I want to display the sublists where length==3 only once.

(我只想显示一次其中length==3的子列表。)

The problem is solved.

(问题已经解决了。)

The problem is with the Eclipse editor.

(问题出在Eclipse编辑器上。)

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?

(我必须在Eclipse中更改任何设置吗?)

  ask by user1188821 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this,

(尝试这个,)

x in mylist is better and more readable than x in mylist[:] and your len(x) should be equal to 3 .

(x in mylist中的x in mylist[:]x in mylist[:]更好,更易读x in mylist[:]并且len(x)应该等于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

(或者如果您需要更多的pythonic使用list-comprehensions)

>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...