2个列表之间的通用元素比较

def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] """ for element in list1: if element in list2: return list(element) 

到目前为止,但似乎无法得到它的工作! 谢谢

 >>> list1 = [1,2,3,4,5,6] >>> list2 = [3, 5, 7, 9] >>> list(set(list1).intersection(list2)) [3, 5] 

S.Mark和SilentGhost提出的解决scheme通常会告诉你如何以Pythonic的方式来完成,但是我认为你也可以从知道你的解决scheme不起作用的原因中获益。 问题是只要你在这两个列表中find第一个公共元素,就只返回那个单一的元素。 您的解决scheme可以通过创build一个result列表并收集列表中的常用元素来解决:

 def common_elements(list1, list2): result = [] for element in list1: if element in list2: result.append(element) return result 

甚至更短的版本使用列表parsing:

 def common_elements(list1, list2): return [element for element in list1 if element in list2] 

但是,正如我所说,这是一个非常低效的方法 – Python的内置集合types更有效率,因为它们是在C内部实现的。

使用set交集,set(list1)&set(list2)

 >>> def common_elements(list1, list2): ... return list(set(list1) & set(list2)) ... >>> >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] >>> >>> 

请注意,结果列表可能与原始列表的顺序不同。

您也可以使用集合并在一行中得到共同点:从包含差异的集合中减去集合。

 A = [1,2,3,4] B = [2,4,7,8] commonalities = set(A) - (set(A) - set(B)) 

以前的答案都是为了find唯一的共同元素,但是不能解释列表中的重复项目。 如果您希望公共元素在列表中显示为相同的数字,则可以使用以下一行代码:

 l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)] 

只有当您期望任何元素评估为False才需要“ or True部分。

1)Method1保存list1是字典,然后迭代list2中的每个元素

def findarrayhash(a,b): h1={k:1 for k in a} for val in b: if val in h1: print("common found",val) del h1[val] else: print("different found",val) for key in h1.iterkeys(): print ("different found",key)查找常用元素和不同元素:

2)使用set的方法2

def findarrayset(a,b): common = set(a)&set(b) diff=set(a)^set(b) print list(common) print list(diff)

我提出了一个相当强悍的方法。 这当然不是最有效的,但是这是一些东西。

我在这里find的一些解决scheme的问题是,它不会给出重复的元素,或者当input顺序很重要时,它不会给出正确数量的元素。

 #finds common elements def common(list1, list2): result = [] intersect = list(set(list1).intersection(list2)) #using the intersection, find the min count1 = 0 count2 = 0 for i in intersect: for j in list1: if i == j: count1 += 1 for k in list2: if i == k: count2 += 1 minCount = min(count2,count1) count1 = 0 count2 = 0 #append common factor that many times for j in range(minCount): result.append(i) return result