繁体   English   中英

Python:确定顺序中的任何项是否与任何其他项相同

[英]Python: determining whether any item in sequence is equal to any other

我想比较多个对象,只有当所有对象彼此不相等时才返回True 我尝试使用下面的代码,但它不起作用。 如果obj1和obj3相等且obj2和obj3不相等,则结果为True

obj1 != obj2 != obj3

我有超过3个对象要比较。 使用下面的代码是不可能的:

all([obj1 != obj2, obj1 != obj3, obj2 != obj3])

@Michael Hoffman的答案很好,如果对象都是可以清洗的。 如果没有,您可以使用itertools.combinations

>>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd', 'a'], 2))
False
>>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd'], 2))
True

如果对象都是可散列的,那么您可以看到对象序列的frozenset集是否与序列本身具有相同的长度:

def all_different(objs):
    return len(frozenset(objs)) == len(objs)

例:

>>> all_different([3, 4, 5])
True
>>> all_different([3, 4, 5, 3])
False

如果对象不可删除但是可订购(例如,列表),那么您可以通过排序将itertools解决方案从O(n ^ 2)转换为O(n log n):

def all_different(*objs):
    s = sorted(objs)
    return all(x != y for x, y in zip(s[:-1], s[1:]))

这是一个完整的实现:

def all_different(*objs):
    try:
        return len(frozenset(objs)) == len(objs)
    except TypeError:
        try:
            s = sorted(objs)
            return all(x != y for x, y in zip(s[:-1], s[1:]))
        except TypeError:
            return all(x != y for x, y in itertools.combinations(objs, 2))
from itertools import combinations
all(x != y for x, y in combinations(objs, 2))

您可以通过将列表中的所有项目转换为集合来检查列表中的所有项目是否都是唯一的。

my_obs = [obj1, obj2, obj3]
all_not_equal = len(set(my_obs)) == len(my_obs)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM