通过列表进行迭代

问题描述:

我是Python的新手.想象一下,我有一个列表 [100,200,300,301,315,345,500] .我想从中创建一个新列表,例如 [100,200,300,500] .

I'm quite a newbie in Python. Imagine I have a list [100, 200, 300, 301, 315, 345, 500]. I want to create a new list out of it, like [100, 200, 300, 500].

当我像这样遍历列表时:

When I iterate through the list like that:

for i in range(len(list)):
    while (list[i+1] - 100) <= list[i]:
        i = i + 1
        k = list[i]

那么while循环中 i 的更改不会反映到for循环中的 i ,因此我对同一元素进行了多次迭代.

Then changes of i within while loop are not reflected for i within for loop, so I iterate multiple times through the same elements.

为了避免这种情况,更改代码的更好方法是什么?

What would be the better way to change the code to avoid that?

这就是我要怎么做

>>> mylist = [100,200,300,301,315,345,500]
>>> [x for x in mylist if x % 100 == 0]
[100, 200, 300, 500]

编辑:在仔细检查算法时,您似乎实际上是在尝试构建一个大于先前值加99的值的列表.在这种情况下,这将起作用:

On closer inspection of your algorithm, it seems you're actually trying to build a list of the values that are larger than the previous value plus 99. In that case, this will work:

def my_filter(lst):
    ret = [lst[0]]
    for i1, i2 in zip(lst, lst[1:]):
        if i2 - i1 >= 100:
            ret.append(i2)
    return ret

上面的算法是这样的:

>>> my_filter([101, 202, 303, 305, 404, 505])
[101, 202, 303, 505]