[英]Fast way to compare items in list with each other for similarity in python
[英]Compare items of list with each other in Python
考虑一个电子邮件列表:
['a@amail.com','b@bmail.com','c@cmail.com',...]
我想比较列表项。 例如,电子邮件将是唯一的。 在Python中比较列表项的方式是什么?
如果您只想测试列表中是否有重复项,您可以使用:
if len(set(list_o_emails)) == len(list_o_emails):
# all are different
else:
# you had a duplicate
raise forms.ValidationError # from your comment
因为set
会为你消除任何重复,并且比较长度将告诉你是否删除了任何重复项。
对于具有列表推导的any()
,这是一个完美的用法:
if any([emails.count(email) > 1 for email in emails]):
raise forms.ValidationError("Emails must be unique.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.