简体   繁体   English

相当于列表中另一个的python项目

[英]python item equivalent to another in list

In python you can check if an item is in a list: 在python中,您可以检查项目是否在列表中:

if item in lst:
   do_stuff()

However, how do I check if a LIKE item is in the list? 但是,如何检查列表中是否有LIKE项目? The is operator checks for the actual object. is运算符检查实际对象。 The in operator does the same. in运算符执行相同的操作。 Is there an equivalent operator of == for in ? in是否有== for的等效运算符?

What I want would be something like 我想要的是

if item is_equal_to_another_in lst:
    do_stuff()

For example: I have a list of [item('a'), item('b'), item('c')] . 例如:我有一个[item('a'), item('b'), item('c')] If I create another item('a') it will be exactly like the one in our list, except it will fail the in statement because the one in our list is a different instance. 如果我创建另一个item('a') ,它将与我们列表中的项目完全一样,除了它将使in语句失败in因为我们列表中的项目是一个不同的实例。

For lists, __contains__ just compares the object with the __eq__ ( == ) operator. 对于列表, __contains__只是将对象与__eq__== )运算符进行比较。 If not defined, it fall through to is . 如果没有定义,它始终陷入is

You probably have to define __eq__ for your specific definition of equality given your items . 对于给定的items您可能必须为特定的平等定义定义__eq__


In this example, I demonstrate how to compare two items based on the value of their attr attribute by performing a case insensitive comparison. 在此示例中,我将演示如何通过执行不区分大小写的比较来基于两个项目的attr属性值比较两个项目。

>>> class item:
...     def __init__(self,attr): self.attr = attr
...     def __eq__(self,o): return isinstance(o, item) and self.attr.lower() == o.attr.lower()
... 
>>> lst = [item("a"), item("b")]
>>> item("A") in lst
True
>>> item("a") in lst
True
>>> item("B") in lst
True
>>> item("C") in lst
False
>>> "A" in lst
False

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

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