【问题标题】:How to check an empty list in Python3如何在 Python3 中检查一个空列表
【发布时间】:2020-11-06 19:04:17
【问题描述】:

我正在尝试使用以下脚本检查我的列表是否为空:

#!/usr/bin/env python3

#First we start with the empty list of "users"
user_names = []

#Run a check with if to see if the list has "users"
if user_names:
    for user in user_names:
        print("Message to user logging in.")
#The assumption is this will evaluate to False and else will execute
    else:
        print("Message when the list is empty.")

但是当脚本被执行时,什么都没有运行并且输出是空白的。我希望知道:

  • 如果这是由于我的代码中的错误?
  • 或者如果它是一个错误?
  • 有没有更好的方法来编写这段代码?

我的 Python 版本是 3.8.3

【问题讨论】:

    标签: list loops boolean python-3.8


    【解决方案1】:

    你的列表是空的,但不是 None(也不是 boolean = False),所以检查 if user_names 总是 True

    所以你的代码总是进入 for 循环,但列表中没有任何内容,所以它什么也不打印。

    您可以像这样检查数组的长度 if len(user_names) == 0:

    【讨论】:

      【解决方案2】:

      缩进是与 python 编程相关的方式。

      如果你运行以下代码:

      user_names = []
      print(f"{user_names} outside the if statement.")
      if user_names:
          print(f"{user_names} inside if statement.")
          for user in user_names:
              print("Message to user logged in.")
          else:
              print("Message when the list is empty.")
      

      你会看到输出是>> [] outside the if statement。这是什么意思?好吧,程序正在跳过if 语句,因为列表是空的,这是意料之中的。但是,else 语句未被读取,因为它位于 if 语句中。这就解释了为什么你得到一个空白输出。所以,下面的代码应该可以解决问题:

      user_names = []
      if user_names:
          for user in user_names:
              print(f"Message to {user} logged in.")
      else:
          print("Message when the list is empty.")
      

      现在,看看代码中的第一个 print() 函数。原代码有两处改动:第一处是f,在开始字符串之前;第二个是用户变量现在位于大括号内:{user}。这两件事一起工作,使循环在适用时打印每个用户名。

      您可以测试将user_names = [] 转换为user_names =["a", "b"] 并再次运行代码。

      你应该得到:

      >> Message to a logged in
      >> Message to b logged in 
      

      最后,我建议使用基于len() 函数的代码来测试if 语句(您可以查看文档here)。这只是为了使您的代码对其他编码人员更具可读性。

      解决方案代码可能如下所示:

      user_names=[]
      if len(user_names)==0:
          for user in user_names:
              print(f"Message to {user} logged in.")
      else:
          print("Message when the list is empty.")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-15
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        • 2017-05-30
        • 2014-04-24
        • 2023-03-22
        • 2020-11-07
        相关资源
        最近更新 更多