[英]Check if there are two (or more) custom object with the same attribute value in a python list
我有這個“問題”:
我有一個包含自定義對象的Python 列表,例如list = [Object1, Object2, Object3, ..., ObjectN]
,我想檢查是否存在一些具有相同屬性值的元素。
因此,如果所有對象具有不同的屬性值,則函數checkDuplicateAttr(list)
應返回 None,否則返回重復屬性對象的列表。
例子:
Foo = newObject(value=1, name="foo")
Bar = newObject(value=4, name="bar")
Car = newObject(value=1, name="car")
list = [Foo, Bar, Car]
if x = checkDuplicateAttr(list) is None:
print("There are no duplicate attribute values")
else:
print("There are duplicate value elements", x)
對於我的示例,輸出應該是:
OUTPUT:
There are duplicate Value elements: [Foo, Car]
請檢查以下代碼是否對您有幫助:
from typing import List
from itertools import groupby
class MyCustomObj:
def __init__(self, value, name):
self.name = name
self.value = value
def __repr__(self):
return self.name
def checkDuplicateAttr(objects: List[MyCustomObj]):
obj_group_by_value = [
list(g[1])
for g in groupby(
sorted(objects, key=lambda obj: obj.value), lambda obj: obj.value
)
]
return list(filter(lambda objs: len(objs) > 1, obj_group_by_value)) or None
Foo = MyCustomObj(value=1, name="foo")
Bar = MyCustomObj(value=4, name="bar")
Car = MyCustomObj(value=1, name="car")
x = checkDuplicateAttr([Foo, Bar, Car])
if x is None:
print("There are no duplicate attribute values")
else:
print(
"There are duplicate value elements {}".format(
x[0] if len(x) == 1 else x
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.