python - 如何确定两个列表在 python 中是否具有相同的属性?
问题描述
对于我的编码项目,我必须使用此代码并查看是否有任何类似的属性。如果是,我需要一个打印语句说“列表具有相似的属性”,如果不是,那么应该有一个打印语句说“两个语句具有相同的属性”。
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)
解决方案
如果要比较单个属性,可以使用
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")
推荐阅读
- laravel - Laravel 自定义表格验证
- python - discord.py:在发布禁令之前,我如何检查用户是否在服务器中?
- javascript - 如何使用在 javascript 中构造的列表遍历 html 中的项目列表?
- linux - 如何使用算术扩展和wc在bash脚本中将单词数与文件的字符数相除
- amazon-web-services - 防止超过一定大小的对象被添加到 S3 的最佳方法是什么?
- javascript - Reactjs 处理状态更改 - 无法读取未定义的属性
- python - 创建一个验证数字是否为二进制且长度为 8 位的函数
- php - 随机分布 PHP/Laravel
- go - golang并发写入具有相同值的uint64变量?
- node.js - Firebase 服务帐户私钥不会在 Node.js 应用程序上解析