Python 3.x 检查列表中是否存在
我有一个有点愚蠢的问题,这几天我都快发疯了。大量的网络搜索也没有帮助 在一些较大的SQLAlchemy应用程序中,我想在执行SQL之前检查列表中是否存在某些值。因此,我定义了两个函数:一个用于检查列表中是否存在值,并返回True或False。加上第二个循环,只要值不在列表中:Python 3.x 检查列表中是否存在,python-3.x,list,Python 3.x,List,我有一个有点愚蠢的问题,这几天我都快发疯了。大量的网络搜索也没有帮助 在一些较大的SQLAlchemy应用程序中,我想在执行SQL之前检查列表中是否存在某些值。因此,我定义了两个函数:一个用于检查列表中是否存在值,并返回True或False。加上第二个循环,只要值不在列表中: def check_value(itemlist, value_check): print(itemlist) #only for debugging reasons if value_check in i
def check_value(itemlist, value_check):
print(itemlist) #only for debugging reasons
if value_check in itemlist:
print('Item is already in list') #only for debugging reasons
return False
else:
print('Item is not in list') #only for debugging reasons
return True
def check_input(itemlist, value_check):
while check_value(itemlist ,value_check)==False:
value_check = input('Please input valid value')
return value_check
[1, 18272, 18279, 12, 298]
Item is not in list
>>>
现在,如果我运行此代码,让我们说:
def check_value(itemlist, value_check):
print(itemlist) #only for debugging reasons
if value_check in itemlist:
print('Item is already in list') #only for debugging reasons
return False
else:
print('Item is not in list') #only for debugging reasons
return True
def check_input(itemlist, value_check):
while check_value(itemlist ,value_check)==False:
value_check = input('Please input valid value')
return value_check
if __name__ == "__main__":
items = [1, 18272, 18279, 12, 298]
value_check = 18272
check_input(items, value_check)
IDLE首先给出了正确的答案:
[1, 18272, 18279, 12, 298]
Item is already in list
Please input valid value
然后我给它一个也在列表中的数字,比如说1,但它仍然告诉我值不在列表中:
def check_value(itemlist, value_check):
print(itemlist) #only for debugging reasons
if value_check in itemlist:
print('Item is already in list') #only for debugging reasons
return False
else:
print('Item is not in list') #only for debugging reasons
return True
def check_input(itemlist, value_check):
while check_value(itemlist ,value_check)==False:
value_check = input('Please input valid value')
return value_check
[1, 18272, 18279, 12, 298]
Item is not in list
>>>
很明显,这已经被问了好几次了,我已经在这里找到了一些帮助:我尝试了这个方法x在上面的代码中
我还发现了这个线程:这将是我检查给定值的索引并围绕它编写一些try/except的变通方法。然而,我不明白为什么x是y在这里不起作用
我有一种感觉,我在这里遗漏了一些非常基本的东西,但我无法理解其中的内容。使用value\u check=intinput'Please input valid value'而不是value\u check=input'Please input valid value'
输入函数返回一个字符串,您的列表只包含数字,从而使while条件为True,即列表中不包含的项使用value\u check=intinput“请输入有效值”而不是value\u check=input“请输入有效值”您有一个整数列表,您的输入会给您一个字符串。您正在检查字符串1是否在列表中,它是否在列表中,只有int值1在列表中-这不是一回事。