代码之家  ›  专栏  ›  技术社区  ›  teddy

Python:查找列表中的所有元素是否都相同,只有两个数字除外

  •  1
  • teddy  · 技术社区  · 6 年前

    我想知道如何检查两个数字列表是否完全相同,除了两个数字

    if list1 == list2: # + except 2 numbers
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   fferri    6 年前

    如果列表元素的顺序很重要,您可以使用以下方法:

    if sum(i != j for i, j in zip(list1, list2)) == 2:
        # the two lists are equal except two elements
    

    如果顺序不重要,重复的元素也无关紧要,那么也可以使用集合交集( & )比较长度:

    if len(set(list1) & set(list2)) == len(list1) - 2:
        # the two list are equal except two elements
    

    如果顺序不重要,但重复的元素很重要,那么使用相同的方法,但要有 collections.Counter :

    from collections import Counter
    if len(Counter(list1) & Counter(list2)) == len(list1) - 2:
        # the two list are equal except two elements
    
        2
  •  2
  •   Cory Kramer    6 年前
    def differ_by_two(l1, l2):
        return sum(1 for i,j in zip(l1, l2) if i!=j) == 2
    

    实例

    >>> differ_by_two([1,2,3],[1,4,5])
    True
    >>> differ_by_two([1,2,3,4,5],[6,7,8,9,10])
    False
    
        3
  •  0
  •   antonwp    6 年前
    def SameBarTwo(l1, l2):
        a = len(l2)
        for i in range(len(l2)):
            if l2[i] in l1:
                l1.remove(l2[i])
                a -= 1
        return a == 2
    

    这将为重复值提供便利,不考虑顺序。