繁体   English   中英

Python-在if语句中列出索引超出范围

[英]Python - list index out of range in if statement

我有一个列表,通常包含项目,但有时为空。

列表中的三项被添加到数据库中,但是即使我使用了if语句,如果它为空,我也会遇到错误。

if item_list[0]:
    one = item_list[0]
else:
    one = "Unknown"

if item_list[1]:
    two = item_list[1]
else:
    two = "Unknown"

if item_list[2]:
    three = item_list[2]
else:
    three = "Unknown"

如果列表为空,这仍然会导致list index out of range错误。 我找不到其他可以完成此操作的方法,但是必须有更好的方法(我还读过您应该避免使用else语句?)

如果列表为空,则列表没有索引; 并尝试访问列表的索引会导致错误。

该错误实际上发生在if语句中。

您可以通过执行以下操作获得期望的结果:

one, two, three = item_list + ["unknown"] * (3 - len(item_list))

这行代码创建了一个临时列表,该列表由item_list和一个(3减去item_list的大小)“未知”字符串的列表组成; 这始终是3个项目的列表。 然后,它将列表分解onetwothree变量


细节:

  • 您可以将一个列表乘以一个包含重复项的更大列表: ['a', 1, None] * 2给出['a', 1, None, 'a', 1, None] 这用于创建“未知”字符串的列表。 请注意,将列表乘以0会得到一个空列表(按预期)。
  • 您可以使用加法运算符来连接2个(或更多)列表: ['a', 'b'] + [1, 2]给出['a', 'b', 1, 2] 这用于从item_list和通过乘法创建的“未知”列表中创建3个项目的列表。
  • 可以解压缩在几个变量的列表与所述分配操作者: a, b = [1, 2]给出a = 1 and b = 2 甚至可以使用扩展解包a, *b = [1, 2, 3]给出a = 1 and b = [2, 3]

例:

>>> item_list = [42, 77]
>>> one, two, three = item_list + ["unknown"] * (3 - len(item_list))
>>> one, two, three
(42, 77, 'unknown')

如果您尝试访问不存在的数组元素,Python将抛出此错误。 因此,空数组不会有索引0。

if item_list:     # an empty list will be evaluated as False
    one = item_list[0]
else:
    one = "Unknown"

if 1 < len(item_list):
    two = item_list[1]
else:
    two = "Unknown"

if 2 < len(item_list):
    three = item_list[2] 
else:
   three = "Unknown"

如果列表中没有2个元素,则item_list[1]将立即引发错误; 这种行为与Clojure之类的语言不同,后者返回的是null值。

使用len(item_list) > 1代替。

您需要检查列表是否足够长,以至于您尝试从中检索的索引位置中都有一个值。 如果您还试图避免在条件语句中使用else ,则可以使用默认值预先分配变量。

count = len(item_list)
one, two, three = "Unknown", "Unknown", "Unknown"
if count > 0:
    one = item_list[0]
if count > 1:
    two = item_list[1]
if count > 2:
    three = item_list[2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM