简体   繁体   English

检查列表中的项目是否存在

[英]Check if item in list is existing

I have list of UUIDs (block_list) and want to check if one specific UUID is listed in that list.我有 UUID 列表(block_list),想检查该列表中是否列出了一个特定的 UUID。

list(block_list)

Out[41]: 
[ ('f779e98c-a541-4ae2-afcb-b0da2e5bee24',),
 ('a005bc7b-c06d-48bf-8259-757d52c70330',),
 ('8af278b1-089e-40e9-a57d-856efe336c26',)]

Why is that giving me a false?为什么这给了我一个假?

'8af278b1-089e-40e9-a57d-856efe336c26' in block_list Answer: False block_list 中的“8af278b1-089e-40e9-a57d-856efe336c26”答案:错误

Thanks Robert谢谢罗伯特

因为 '8af278b1-089e-40e9-a57d-856efe336c26' 是一个字符串,但您的列表由元组组成

The reason it is false because you are checking if a string is in a list.之所以为 false,是因为您正在检查字符串是否在列表中。 But your list is a list of the tuples.但是您的列表是元组列表。 So you have to check if any particular tuple is in the list.所以你必须检查列表中是否有任何特定的元组。

So instead you need following codes:因此,您需要以下代码:

('8af278b1-089e-40e9-a57d-856efe336c26') in block_list

Now the output will be True现在输出将为 True

You should pass a string inside a tuple, do not pass the raw string to see if it's in the list.您应该在元组中传递一个字符串,不要传递原始字符串以查看它是否在列表中。 Here is a simple function that can do it for you by passing a raw string and nesting it inside a tuple with a trailing comma:这是一个简单的函数,它可以通过传递原始字符串并将其嵌套在带有尾随逗号的元组中来为您完成:

def check_string(string):
    if ((string, ) in my_list):
        return True
    else:
        return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM