我有一个列表,通常包含项目,但有时是空的。
列表中的三个项被添加到数据库中,但如果它是空的,即使我使用的是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语句吗?)
发布于 2017-05-05 15:04:35
如果列表为空,则该列表没有索引;尝试访问该列表的索引将导致错误。
错误实际上发生在if语句中。
通过这样做,您可以获得预期的结果:
one, two, three = item_list + ["unknown"] * (3 - len(item_list))这一行代码创建了一个临时列表,该列表由item_list的连接和(3减去item_list的大小)“未知”字符串组成;该列表始终是一个3项列表。然后,它在解包、two和three变量中列出这个列表。
详情:
['a', 1, None] * 2给出['a', 1, None, 'a', 1, None]。这用于创建“未知”字符串的列表。注意,将列表乘以0会导致空列表(如预期的那样)。['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')发布于 2017-05-05 15:05:37
如果您试图访问不存在的数组元素,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"发布于 2017-05-05 15:04:13
如果列表中没有2个元素,item_list[1]将立即引发错误;该行为与Clojure等语言的行为不同,后者返回一个空值。
使用len(item_list) > 1代替。
https://stackoverflow.com/questions/43808194
复制相似问题