【发布时间】:2018-06-19 00:54:13
【问题描述】:
我有一个有点愚蠢的问题,这几天让我发疯了。繁重的网络搜索也无济于事。
在一些较大的 SQLAlchemy 应用程序中,我想检查某个值是否存在于列表中(在执行 SQL 之前)。因此,我定义了两个函数:一个检查列表中是否存在值,并返回 True 或 False。加上第二个循环,只要值不在列表中:
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
现在如果我运行这段代码,让我们说:
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”,但它仍然告诉我该值不在列表中:
[1, 18272, 18279, 12, 298]
Item is not in list
>>>
很明显,这已经被问过好几次了,我已经在这里找到了一些帮助:How to check if a specific integer is in a list我试过这个方法 x is in(见上面的代码)。
我还发现了这个线程:Finding the index of an item given a list containing it in Python,这将是我检查给定值的索引并在其周围写一些 try/except 的解决方法。不过我不明白为什么 x is y 在这里不起作用。
我觉得我在这里遗漏了一些非常基本的东西,但我无法掌握什么。
【问题讨论】:
-
使用
value_check = int(input('Please input valid value'))而不是value_check = input('Please input valid value') -
您有一个
list或integers,您的input给您一个string。您正在检查string1是否在list中,但它不是,只有1的int在 - 这不是一回事。
标签: python-3.x list