簡體   English   中英

Python檢查對象是否在對象列表中

[英]Python check if object is in list of objects

我在Python中有一個對象列表。 然后我有另一個對象列表。 我想瀏覽第一個列表,看看是否有任何項目出現在第二個列表中。

我以為我可以做到

for item1 in list1:
    for item2 in list2:
        if item1 == item2:
            print "item %s in both lists"

然而,這似乎不起作用。 雖然我這樣做:

if item1.title == item2.title:

它工作正常。 我有比這更多的屬性,所以不要真的想做一個大的if語句比較所有的屬性,如果我不需要。

任何人都可以給我幫助或建議我可以做什么來找到兩個列表中出現的對象。

謝謝

假設您的對象只有一個與相等相關的title屬性,您必須按如下方式實現__eq__方法:

class YourObject:
    [...]
    def __eq__(self, other):
        return self.title == other.title

當然,如果您有更多與平等相關的屬性,那么您也必須包含這些屬性。 您也可以考慮實現__ne____cmp__以保持一致的行為。

如果對象不是同一個實例,則需要為python實現__eq__方法,以便能夠判斷2個對象實際上是否相等。

當然,大多數庫類型,例如字符串和列表已經實現了__eq__ ,這可能是比較標題適合你的原因(它們是字符串嗎?)。

有關更多信息,請參閱python文檔
這是__eq__隨機示例

集合交叉將為此做。

>>> x=[1,2,3,4]
>>> y=[3,4,5,6]
>>> for i in set(x) & set(y):
...     print "item %d in both lists" %i
...
item 3 in both lists
item 4 in both lists

查找出現在兩個列表中的對象:

l1 = [1,2,3,4,5]
l2 = [3,4,5]
common = set(l1).intersection(set(l2))

將其與對象上的__eq__實現相結合,如其他人所建議的那樣。

您需要編寫__eq__函數來定義如何比較對象的相等性。 如果你想要排序,那么你應該有一個__cmp__函數,並且根據__cmp__實現__eq__是最有意義的。

def __eq__(self, other):
    return cmp(self, other) == 0

您可能還應該實現__hash__ ,如果您計划將對象放入集合或字典中,那么您肯定應該這樣做。 對象的默認__hash__是id(),它有效地使所有對象都是唯一的(即唯一性不基於對象內容)。

我為一個類做了基類/接口,它進行了這種等價比較。 您可能會發現它很有用:

class Comparable(object):
    def attrs(self):
        raise Exception("Must be implemented in concrete sub-class!")
    def __values(self):
        return (getattr(self, attr) for attr in self.attrs())
    def __hash__(self):
        return reduce(lambda x, y: 37 * x + hash(y), self.__values(), 0)
    def __cmp__(self, other):
        for s, o in zip(self.__values(), other.__values()):
            c = cmp(s, o)
            if c:
                return c
        return 0
    def __eq__(self, other):
        return cmp(self, other) == 0
    def __lt__(self, other):
        return cmp(self, other) < 0
    def __gt__(self, other):
        return cmp(self, other) > 0

if __name__ == '__main__':
    class Foo(Comparable):
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def attrs(self):
            return ('x', 'y')
        def __str__(self):
            return "Foo[%d,%d]" % (self.x, self.y)

    def foo_iter(x):
        for i in range(x):
            for j in range(x):
                yield Foo(i, j)

    for a in foo_iter(4):
        for b in foo_iter(4):
            if a<b: print "%(a)s < %(b)s" % locals()
            if a==b: print "%(a)s == %(b)s" % locals()
            if a>b: print "%(a)s > %(b)s" % locals()

派生類必須實現attrs() ,它返回對象的屬性的元組或列表,這些屬性有助於其身份(即,使其成為現實的不變屬性)。 最重要的是,代碼正確處理具有多個屬性的等效性,這是通常不正確的舊學校代碼。

matches = [x for x in listA if x in listB]

請嘗試以下方法:

list1 = [item1, item2, item3]
list2 = [item3, item4, item5]
for item in list1:
    if item in list2:
        print "item %s in both lists" % item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM