gpt4 book ai didi

Python:查找列表中的所有元素是否都相同,除了恰好 2 个数字

转载 作者:太空宇宙 更新时间:2023-11-04 09:44:21 25 4
gpt4 key购买 nike

我想知道如何检查两个数字列表是否相同,除了恰好 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com