我想知道如何检查两个数字列表是否相同,除了恰好 2 个数字
if list1 == list2: # + except 2 numbers
最佳答案
如果列表元素的顺序很重要,你可以使用这样的东西:
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
关于Python:查找列表中的所有元素是否都相同,除了恰好 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380800/