当条件为真时,我试图从列表中删除项目,然后从列表的最开始再次迭代。以下是我的代码:
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.如何每次列表获取时从一开始就重新启动循环更新? 谢谢!
答案 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]