我想要比较多个对象,并且仅当所有对象之间不相等时才返回True。我尝试使用下面的代码,但它不起作用。如果obj1和obj3相等,而obj2和obj3不相等,则结果为True。
obj1 != obj2 != obj3我有3个以上的对象要比较。使用下面的代码是不可能的:
all([obj1 != obj2, obj1 != obj3, obj2 != obj3])发布于 2012-07-31 04:01:25
@Michael Hoffman的答案是好的,如果对象都是hashable的。如果没有,您可以使用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发布于 2012-07-31 03:59:24
如果对象都是hashable的,那么您可以看到对象序列的frozenset是否与序列本身具有相同的长度:
def all_different(objs):
return len(frozenset(objs)) == len(objs)示例:
>>> all_different([3, 4, 5])
True
>>> all_different([3, 4, 5, 3])
False发布于 2012-07-31 05:02:05
如果对象是不可散列但可排序的(例如,列表),则可以通过排序将itertools解决方案从O(n^2)转换为O( 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))https://stackoverflow.com/questions/11728662
复制相似问题