簡體   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