从列表中有条件地删除项目并从开始迭代到Python循环

时间:2017-11-21 04:08:38

标签: python python-3.x loops for-loop while-loop

当条件为真时,我试图从列表中删除项目,然后从列表的最开始再次迭代。以下是我的代码:

from random import randint
x = [1,2,3,4,5]

for item in x:
    print("item is " + str(item))
    z = randint(1, 5)
    print("z is " + str(z))
    if z == item:
        x[:] = [item for item in x if item != z]
        print("Remaining list is " + str(x))
    else:
        print("Remaining list is " + str(x))

例如,我x列表中的第一个项目是1,并且假设z也是1.当z == item时,我的x列表会删除第一个项目(1)和更新到[2,3,4,5]。但我得到以下输出:

item is 1
z is 1
Remaining list is [2, 3, 4, 5]
item is 3
z is 2
Remaining list is [2, 3, 4, 5]

而不是在我最近更新的列表[2,3,4,5]中从2重新启动循环,循环从第二个位置开始,即3.如何每次列表获取时从一开始就重新启动循环更新? 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在while循环之外添加for循环,并在删除项目时重新启动for循环。

from random import randint
x = [1,2,3,4,5]

restart = True

while restart:
    restart = False
    for item in x:
        print("item is " + str(item))
        z = randint(1, 5)
        print("z is " + str(z))
        if z == item:
            x[:] = [item for item in x if item != z]
            print("Remaining list is " + str(x))
            restart = True
            break
        else:
            print("Remaining list is " + str(x))

# results
item is 1
z is 2
Remaining list is [1, 2, 3, 4, 5]
item is 2
z is 2
Remaining list is [1, 3, 4, 5]
item is 1
z is 1
Remaining list is [3, 4, 5]
item is 3
z is 4
Remaining list is [3, 4, 5]
item is 4
z is 3
Remaining list is [3, 4, 5]
item is 5
z is 5
Remaining list is [3, 4]
item is 3
z is 4
Remaining list is [3, 4]
item is 4
z is 1
Remaining list is [3, 4]

答案 1 :(得分:1)

For循环不会按照您预期的方式运行,如果您可以使用while进行条件检查,那么效果会更好:

from random import randint
    x = [1, 2, 3, 4, 5]
    loops = 0
    while loops<len(x):
        item = x[loops]
        print("item is " + str(item))
        z = randint(1, 5)
        print("z is " + str(z))
        if z == item:
            x[:] = [item for item in x if item != z]
            print("Remaining list is " + str(x))
            continue
        else:
            print("Remaining list is " + str(x))
        loops += 1

输出:

item is 1
z is 1
Remaining list is [2, 3, 4, 5]
item is 2
z is 2
Remaining list is [3, 4, 5]
item is 3
z is 1
Remaining list is [3, 4, 5]
item is 4
z is 2
Remaining list is [3, 4, 5]
item is 5
z is 1
Remaining list is [3, 4, 5]