查找多个数组的元素数

时间:2017-03-31 03:02:05

标签: python list

给定两个列表我需要制作第三个列表,其中包含在所有列表1和列表2中仅出现两次的元素。 如何以合理的时间和空间复杂度来提高效率?

我的解决方案: 使用字典:

from collections import defaultdict


L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result

我想要的输出是:

['e', 'd', 'i', 'r']

我可以获得更好的pythonic解决方案吗?

感谢。

3 个答案:

答案 0 :(得分:3)

您可以使用集合的计数器类来简化代码:

from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once

此外,您可以通过执行条件for循环来组合行。所以只有当值为2时,我们才会将它附加到我们的数组中。

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]

答案 1 :(得分:2)

您可以使用python In [796]: img = np.arange(12).reshape(3,4) In [797]: img = img.flatten() In [798]: img.shape Out[798]: (12,) In [799]: X = np.stack([img,img,img,img,img],0) In [800]: X = np.stack([img,img,img,img,img,img],0) In [801]: X.shape Out[801]: (6, 12) In [802]: X1 = X.reshape(2,3,3,4) In [803]: X2 = X1.transpose([0,2,3,1]) In [804]: X2.shape Out[804]: (2, 3, 4, 3) In [805]: X2[0,:,:,0] Out[805]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) 来获取列表中每个单词的计数。 https://docs.python.org/2/library/collections.html#counter-objects

Counter

执行此迭代计数器对象后,将元素添加到第三个列表中,其值为2。

答案 2 :(得分:0)

这在空间复杂性方面效果很好,它也是pythonic,但我对运行时间不太确定

set([x for x in L.extend(K) if L.extend(K).count(x) == 2])  

请注意,这会返回一个集合而不是列表!

相关问题