【问题标题】:Check for existence in list [duplicate]检查列表中是否存在[重复]
【发布时间】: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')
  • 您有一个listintegers,您的input 给您一个string。您正在检查 string 1 是否在 list 中,但它不是,只有 1int 在 - 这不是一回事。

标签: python-3.x list


【解决方案1】:

使用value_check = int(input('Please input valid value')) 而不是value_check = input('Please input valid value') input 函数返回一个字符串,并且您的列表仅包含数字,从而使 while 条件 True 即项目不在列表中

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2019-05-28
    • 2011-02-25
    • 1970-01-01
    • 2020-09-14
    • 2019-03-19
    • 2012-06-15
    • 2015-10-06
    • 2012-02-18
    相关资源
    最近更新 更多