在Python中循环遍历列表

问题:在Python中循环遍历列表

我有一个带有子列表的列表。我想打印长度等于3的所有子列表。

我在python中执行以下操作:

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

values是原始列表。上面的代码是否打印每个值等于3的子列表x?我只想显示length == 3一次子列表。

问题已经解决了。问题出在Eclipse编辑器上。我不明白原因,但是在运行循环时,它仅显示列表的一半。

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

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?


回答 0

试试这个,

x in mylistx 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]

或者,如果您需要更多的Python语言,请使用list-comprehensions

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

Try this,

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]]
>>>

回答 1

您最好使用for x in values而不是for x in values[:]; 后者制作了不必要的副本。另外,当然,该代码检查的长度为2而不是3 …

该代码仅针对x-的值打印一项,并x在的元素(values即子列表)上进行迭代。因此,它将只打印每个子列表一次。

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3…

The code only prints one item per value of x – and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.


回答 2

这是我一直在寻找的解决方案。如果要创建包含List1中数字元素之差的List2。

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

请注意,虽然len(list1)is是11(元素),但len(list2)将仅是10个元素,因为我们是从list1中索引为1的元素而不是list1中索引为0的元素开始for循环的

Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

Note that while len(list1) is 11 (elements), len(list2) will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1


回答 3

而是这样做:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)