[英]Fastest way of finding common elements between two list of lists in python
[英]Finding the common item between two list in python
大家好,我在過去的測試問題上需要幫助。 基本上給了我兩個對象列表,並且我想找到出現在第一個列表和第二個列表相同位置的項目數。 我有一個例子。
>>> commons(['a', 'b', 'c', 'd'], ['a', 'x', 'b', 'd'])
2
>>> commons(['a', 'b', 'c', 'd', 'e'], ['a', 'x', 'b', 'd'])
2
我在寫代碼時遇到麻煩。 我們的課使用的是python3。我不知道從哪里開始編寫。 這是一門第一年的編程課程,我一生中從未做過編程。
我認為更簡單的解決方案是:
def commons(L1,L2):
return len([x for x in zip(L1,L2) if x[0]==x[1]])
對於初學者來說,這不是一個簡單的問題。 一種更直接的方法是使用諸如sum
和zip
類的函數,並具有如下列表理解功能:
def commons(L1, L2):
return sum(el1 == el2 * 1 for el1, el2 in zip(L1, L2))
初學者采用的更典型但容易出錯的方法是:
def commons(L1, L2):
count = 0
for i, elem in enumerate(L2):
if elem == L1[i]:
count += 1
return count
我說這更容易出錯,因為有更多部分需要糾正。
不使用enumerate
您可以執行以下操作:
def commons(L1, L2):
count = 0
for i, range(len(L2)):
if L1[i] == L2[i]:
count += 1
return count
但是前兩個僅在len(L2) <= len(L1)
。 明白我的意思是更容易出錯嗎? 要解決此問題,您需要執行以下操作:
def commons(L1, L2):
count = 0
for i, range(min(len(L2), len(L1))):
if L1[i] == L2[i]:
count += 1
return count
似乎這樣可以工作:
def commons(l1, l2):
return sum(1 for v1,v2 in map(None, l1,l2) if v1 == v2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.