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

标签 python list numbers int

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

相关文章:

python - 为什么这种切片代码比更多的过程代码更快?

python - 通过 JSON 将 Django 数据库查询集传递给 Highcharts

python - 将 Django 部署到 Heroku - 服务器错误 (500)

python - Conda - 离线安装/更新

python - 如何检查变量是 python 列表、numpy 数组还是 pandas 系列

css - 大小相等的列表项

python - 构建列表

Java - 按四分之一间隔舍入

javascript - 如何在文档中找到所有数字并设置它们的样式?

android - 在每个特定值android之后显示一个对话框