2017-04-07 85 views
-2

我發現任何存在的兩個列表的任何重疊元素,並將其轉換爲整數。切片可能的空列表Python

list_converter = intersection[0] 

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

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

有沒有更好的方法來做到這一點,或避免錯誤,當沒有列表爲空?

+1

那你想讓它列表爲空時返回?請發佈輸入和期望的輸出。 –

+0

就這樣它不會導致錯誤。我很好,它沒有返回。 – Detterman

回答

0
list(set(list1).intersection(list2)) 
+1

會這樣做修復IndexError?請提供更多細節。 – Kevin

0

您可以檢查列表的長度與if語句:

if len(intersection) > 0: 
    list_converter = intersection[0] 
else: 
    print "List is empty!" 
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,因此可以使用其真值檢查空列表。

0

如果你想獲得一個空列表時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