![](/img/trans.png)
[英]Python Web Scraping - How To Skip Non-Existent Elements In Iteration
[英]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
的值賦給x
; 如果不存在 , 則將其賦值給x
。
這是我的挑戰: myList
最多可以包含三個元素,但並不總是具有三個。 因此,如果索引不存在(即,如果所討論的索引比列表的大小大1+),那么IndexError list out of range
聯條件可以分配變量之前,我顯然會獲得IndexError list out of range
的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的所有調用均成功,我將獲得完整列表,一切正常。 但是,如果只有兩個返回一個值,則列表僅包含兩個項目,但是我不知道哪個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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.