在python中,如何确定两个列表是否具有相同的属性?

2024-09-30 08:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的编码项目,我必须使用这段代码,看看是否有类似的属性。如果是的话, 我需要一个print语句说“列表具有相似的属性”,如果没有,那么应该有一个print语句说“这两个语句具有相同的属性”

class Box:
    def __init__(self, date1, contents1, location1):
        self.date = date1
        self.contents = contents1
        self.location = location1


box23 = Box("2016", "medical records", "storage closet")
box21 = Box("2018", "lotion samples", "waiting room")
box07 = Box("2020", "flyers for flu shot", "receptionist desk")
print(box23.date)
print(box21.contents)
print(box07.location)

Tags: selfbox编码date属性contentslocation语句
2条回答

如果要获取两个对象上的所有属性:

def get_matching_attributes(instance1, instance2):
    return [attribute for attribute in instance1.__dict__ if attribute in instance2.__dict__]

->;返回所有匹配属性的列表


如果要获取位于对象的所有属性也具有相同的值:

确保您还获得了上面定义的函数get_matching_attributes,以便使用

def compare_matched_attribute_values(instance1, instance2):
    matching_attributes = get_matching_attributes(instance1, instance2)
    matching_values = []
    for attribute in matching_attributes:
        if instance1.__dict__[attribute] == instance2.__dict__[attribute]:
            matching_values.append((attribute, True))
        else:
            matching_values.append((attribute, False))
    return [obj[0] for obj in matching_values if obj[1] is True]

->;返回也具有相同值的所有匹配属性的列表

提示:如果要获取tuble中所有匹配属性的列表,请将最后一列更改为return matching_values,其中TrueFalse指示属性在两个对象中是否具有相同的值

如果要比较单个属性,可以使用

if box23.date == box21.date:
    print("boxes have the same date")
else:
    print("boxes have different dates")

如果要比较所有属性,只需比较__dict__属性即可:

if box23.__dict__ == box21.__dict__:
    print("boxes have the same attributes")
else:
    print("boxes don't have the same attributes")

相关问题 更多 >

    热门问题