有没有更好的方法来确定对象是否在python中的列表中?

时间:2015-04-07 02:02:06

标签: list python-3.x

在python中我想创建一个函数,如果列表中有内容,则返回true。这是我的示例代码。

def isin(List, value):
    try:
        i = List.index(value)
    except ValueError:
        return False
    return True

例如,如果我这样做

myList = [0,1,'string', 4.8]

isin(myList, 1) # I want to return True
isin(myList, 'animal') # I want to return False

2 个答案:

答案 0 :(得分:1)

if 1 in myList         # true
if "animal" in myList  # false

答案 1 :(得分:1)

Python内置了in运算符:

myList = [0,1,'string', 4.8]

if 1 in myList:
    # Do something
    pass 

print('animal' in myList) # Prints 'False'.