[英]Python:Find if all elements in lists are the same except exactly 2 numbers
我想知道如何检查两个数字列表是否相同,但恰好是两个数字
if list1 == list2: # + except 2 numbers
def differ_by_two(l1, l2):
return sum(1 for i,j in zip(l1, l2) if i!=j) == 2
Example 例
>>> differ_by_two([1,2,3],[1,4,5])
True
>>> differ_by_two([1,2,3,4,5],[6,7,8,9,10])
False
If order of list elements is important, you can use something like this: 如果列表元素的顺序很重要,则可以使用以下方法:
if sum(i != j for i, j in zip(list1, list2)) == 2:
# the two lists are equal except two elements
If order is not important, and repeated elements do not matter, you could also use set intersection ( &
) and compare length: 如果顺序不重要,并且重复元素也没有关系,则还可以使用设置交集( &
)并比较长度:
if len(set(list1) & set(list2)) == len(list1) - 2:
# the two list are equal except two elements
If order is not important, but repeated elements matter, use the same approach, but with collections.Counter
: 如果顺序不重要,但是重复的元素很重要,则使用相同的方法,但要使用collections.Counter
:
from collections import Counter
if len(Counter(list1) & Counter(list2)) == len(list1) - 2:
# the two list are equal except two elements
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
This will make accommodations for duplicate values, order is not taken into account. 这样可以容纳重复的值,而不考虑订单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.