【问题标题】:while loop list pythonwhile循环列表python
【发布时间】:2021-11-13 18:40:05
【问题描述】:

我有以下代码检查该元素是否在列表中,如果找到该元素,然后它会将其添加到警报中,因此在一个 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

【问题讨论】:

  • 为什么代码中有“while True:”?
  • 我在不同的代码上使用了相同的逻辑。

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


【解决方案1】:

当您使用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)

【讨论】:

  • 我怎样才能从一个while循环中做到这一点。代码必须永远运行,但警报应该只出现一次。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    你没有改变i,所以它会无休止地寻找相同的元素

    【讨论】:

      【解决方案4】:

      原因是“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,如果我们这样做,它将不断输出存在,​​因为 i = 1 是一个常数。

      上面我写的代码是得到你想要的结果的正确方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        • 2014-11-02
        • 1970-01-01
        • 2011-06-23
        • 2013-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多