Python: 如何在不获取 IndexError 的情况下检查不存在的列表元素的值?

Python: How to check the value of a non-existent list element without getting IndexError?

我正在使用 Python 的单行条件语句:

x = 'foo' if myList[2] is not None else 'bar'

分配给 x 列表特定索引处的项目的值 - 当且仅当它存在时 - 如果不存在则分配不同的值't.

这是我的挑战:myList 最多可以有三个元素,但不一定总是三个。因此,如果索引不存在(即,如果所讨论的索引比列表的大小大 1+),我显然会在内联条件可以分配变量之前得到一个 IndexError list out of range

In [145]: myList = [1,2]

In [146]: x = 'foo' if myList[2] is not None else 'bar'
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-146-29708b8c471e> in <module>()
----> 1 x = 'foo' if myList[2] is not None else 'bar'

IndexError: list index out of range

事先检查列表的长度并不是一个真正的选择,因为我不知道缺少我感兴趣的哪个值(即 myList 可能缺少三个可能值中的任何一个或全部. 知道它只包含一个,或者两个,或者三个元素也无济于事)。

更新:我无法根据列表长度赋值的原因如下。该列表的最大大小为 3,顺序很重要。填充的值将是对 API 的三个单独调用的结果。如果对 API 的所有调用都成功,我会得到一个完整的列表,一切都很好。然而如果只有两个return一个值,列表只包含两个项目,但我不知道哪个API调用导致了丢失的项目,所以分配变量是运气。

所以,长话短说:如何检查某个索引处不存在的列表项,同时保持 Python 的单行条件?

测试是否有足够的元素:

x = 'foo' if len(myList) > 2 and myList[2] is not None else 'bar'

如果缺少前 2 个元素或者您有超过 3 个元素都没有关系。重要的是列表足够长,可以在第一位放置第三个元素。

使用尝试。

#!/usr/bin/python
# -*- coding: utf-8 -*-

L=[1,2,3]

i=0
while i < 10:
    try:
        print L[i]

    except IndexError as e:
        print e, 'L['+str(i)+']'

    i += 1

输出

1
2
3
list index out of range L[3]
list index out of range L[4]
list index out of range L[5]
list index out of range L[6]
list index out of range L[7]
list index out of range L[8]
list index out of range L[9]