我有两个列表,需要检查它们是否包含相同顺序的相同对象。
list1 = [object1 , object2 , object3]
list2 = [object1 , object2 , object3]
list3 = [object2 , object3 , object1]
比较列表list1
和list2
,结果应为true
。
比较列表list1
和list3
,结果应为false
。
编辑:示例列表示例:list = [[<object1 at 0x04130AB0>], [<object2 at 0x04130210>, <object3 at 0x04130A10>]]
答案 0 :(得分:2)
基本==
只会检查一个list
中的每个元素是否等于另一个list
中的相应元素。但是,根据lst = [[<object1 at 0x04130AB0>], [<object2 at 0x04130210>, <object3 at 0x04130A10>]]
的示例,您正在尝试检查身份。具有不同身份的两个对象可以比较为“相等”,这取决于该类的定义。以下是==
告诉您两个list
包含相同顺序的相同对象的示例:
>>> import collections
>>> a = collections.Counter()
>>> b = collections.Counter()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> class Person:
... def __eq__(self, other):
... return True
...
>>> a = Person()
>>> b = Person()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> a = []
>>> b = []
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> a.append(0)
>>> l1 == l2
False
如果要检查相应的元素实际上是同一个对象(标识,而不是相等),则需要以某种方式手动比较标识,如下所示:
>>> import collections
>>> a = collections.Counter()
>>> b = collections.Counter()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
>>> a = Person()
>>> b = Person()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
>>> a = []
>>> b = []
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
答案 1 :(得分:1)
简单,只需使用SELECT REGEXP_COUNT(employeename, 'L', 1, 'c') NumberOfL,
employeename FROM employee
来共同编制两个列表。如果两个列表具有相同的元素并且应该以相同的顺序放置,那么这应该返回==
,否则返回True
False
实现上述逻辑的函数应该是,
list1 == list2
例如:
def check_lists(list1, list2):
return list1 == list2
答案 2 :(得分:0)
假设T&C在身份平等方面的身份很重要。
def check_id(li1, li2):
return [id(o) for o in li1] == [id(o) for o in li2]