2017-04-07 78 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