【问题标题】:Slicing Possible Empty List Python切片可能的空列表 Python
【发布时间】:2017-04-07 19:07:09
【问题描述】:

我正在查找两个列表的任何重叠元素(如果存在),并将其转换为整数。

list_converter = intersection[0]

它返回一个只有一个值或没有值的列表。如果没有值,我得到:

    list_converter = intersection[0]
IndexError: list index out of range

有没有更好的方法来做到这一点,或者在没有列表为空时避免错误?

【问题讨论】:

  • 当列表为空时你希​​望它返回什么?请发布输入和预期输出。
  • 只是为了不引起错误。我什么都不返回也没关系。

标签: python list error-handling slice


【解决方案1】:

你可以这样做:

if intersection:
    list_converter = intersection[0]
else:
    print "No intersection" # Or whatever you want to do if there isn't an intersection

在 python 中,空列表(即[])评估为False,因此可以检查空列表是否使用其真值。

【讨论】:

    【解决方案2】:

    您可以使用 if 语句检查列表的长度:

    if len(intersection) > 0:
        list_converter = intersection[0]
    else:
        print "List is empty!"
    

    【讨论】:

      【解决方案3】:

      如果您想在intersection 为空时获取一个空列表,您可以使用:

      list_converter = intersection[0:1]
      

      当切片的末尾超出列表末尾时不会引发错误:

      l = [1, 2 ,3]
      l[0:1]
      # [1]
      
      l = []
      l[0:1]
      #[]
      

      如果您想要其他内容,请使用 try / except 块:

      try:
          list_converter = intersection[0]
      except IndexError:
          list_converter = whatever you want
      

      【讨论】:

        【解决方案4】:
        list(set(list1).intersection(list2))
        

        【讨论】:

        • 这样做会修复 IndexError 吗?请提供更多细节。
        猜你喜欢
        • 2014-04-24
        • 2018-12-02
        • 1970-01-01
        • 2017-06-24
        • 2015-02-19
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多