while 循环列表 python

while loop list python

我有以下代码检查该元素是否在列表中,如果已找到该元素,那么它会将其添加到警报中,从而在 while 循环中该元素将显示为 exists 一次.

test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
while True:
    
    i = 1
    if i in test_list and (i != alert):
        print('exists')
        alert.append(i)

但是它在不停地打印exist。如果在列表中找到该元素,它只打印 1 次 exists

,请告知我需要做什么

alert.append(i)之后添加一个break语句,因为满足条件需要退出循环。您的循环设置为 true 因此您需要使用 break 退出循环。如果从未满足条件,您还将无限次地遍历列表。您应该尝试使用 for 循环最多遍历列表一次。

if i in test_list and (i != alert):
    print('exists')
    alert.append(i)
    break

当您使用 while True: 时,其中的代码将永远 运行 直到您 break

因此在您的代码中,我认为您需要这样做:

test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
for i in test_list:
    if not i in alert:
        print('exists')
        alert.append(i)

编辑: 如果你想 运行 永远:

test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
while True:
    for i in test_list:
        if not i in alert:
            print('exists')
            alert.append(i)

你没有改变i所以它会不断地找到相同的元素

原因是“while True”循环将 运行 无限。

您可以像这样使用 for 循环:

test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
n = len(test_list)

for i in range(0, n): 
    if i == 1:
        print('exists')
        alert.append(i)

但是你的程序有一个错误。自然 i != alert 因为警报列表中没有任何内容。而且我们不需要写 i = 1 如果我们这样做,它会不断输出 exists 因为 i = 1 是一个常数。

我编写的上述代码是获得所需结果的正确方法。