python - Python比较和区分自定义对象
问题描述
如何比较两个对象列表?
这是对象的定义:
class Form:
def __init__(self,name, value):
self.name = name;
self.value = value;
def __eq__(self, other):
return self.name == other.name and self.value == other.value;
现在我有这个对象“表单”的两个不同列表。我怎么能比较呢?我必须找到:
- 相同的名称和价值
- 名称相同但值不同
- 与第一个列表不同的名称
- 与第二个列表不同的名称
谢谢你。
解决方案
您要比较的最后 2 个选项是相同的,如果您要比较两个项目并且名称不同,那么你们两个都是不同的。
lst_1 = [Form('a', 1), Form('b', 2), Form('c', 3)]
lst_2 = [Form('a', 1), Form('b', 0), Form('d', 3)]
if len(lst_1) != len(lst_2):
print("WARNING: lists are of different sizes, checking the first elements")
for a, b in zip(lst_1, lst_2):
if not isinstance(a, Form) or not isinstance(b, Form):
raise TypeError
if a == b: # Both name and valua are equal
print("They are the same Form")
elif a.name == b.name: # Only names are equal
print("They have the same name but different value")
else: # Names are different
print("They have different names")
将输出:
They are the same Form
They have the same name but different value
They have different names
推荐阅读
- php - WordPress WooCommerce 自定义支付网关开发问题
- reactjs - 无法将解构的道具分配给 react-bootstrap 组件
- ios - 在应用程序购买失败“无法连接到 iTunes Store”错误
- r - 使用 R 计算大数据集中每一行的情绪
- javascript - Javascript:转义字符(\b、\f、\v)是否可以安全地用作用户输入数据和 localStorage 的连接符?
- python-3.x - manjaro上的VS-CODE错误,自动退出,无法打开文件夹
- python - 模块 ctypes 没有属性“windll”
- r - 如何解决 RStudio 中的包安装问题?
- java - 如何在带有指示器的 android java 中创建范围搜索栏?
- flutter - 如何同时使用 FutureBuilder 和 setState 方法?(Flutter)