[英]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
例
>>> 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 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
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
這樣可以容納重復的值,而不考慮訂單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.