两个列表中的独特元素

时间:2016-01-09 06:15:08

标签: python

我在考虑是否可以从两个较短的列表中创建一个独特元素列表但不使用set

l1 = [1,1,2,2,3]
l2 = [2,1,3,3,4]
unique = []
for elem in l1+l2:
    if elem not in unique:
        unique.append(elem)
print unique

[1,2,3,4]

感谢您的想法

2 个答案:

答案 0 :(得分:2)

首先,您应该在Python中使用set来查找唯一值,因为它可以有效地为您提供唯一元素。

如果您想使用list,那么您提供的代码是正确的!如果您在代码中使用numpy(对于大量数据可能是一个不错的选择),请查看numpy.unique

>>> import numpy as np
>>> wordsList = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
>>> np.unique(wordsList)
array([u'PBS', u'debate', u'job', u'nowplaying', u'thenandnow'], 
      dtype='<U10')

另请查看此基准测试结果,以查找unique values Link

代码在链接上提供,但在此处添加供您参考:

def f1(seq):
   # not order preserving
   set = {}
   map(set.__setitem__, seq, [])
   return set.keys()

def f2(seq): 
   # order preserving
   checked = []
   for e in seq:
       if e not in checked:
           checked.append(e)
   return checked

def f3(seq):
   # Not order preserving
   keys = {}
   for e in seq:
       keys[e] = 1
   return keys.keys()

def f4(seq): 
   # order preserving
   noDupes = []
   [noDupes.append(i) for i in seq if not noDupes.count(i)]
   return noDupes

def f5(seq, idfun=None): 
   # order preserving
   if idfun is None:
       def idfun(x): return x
   seen = {}
   result = []
   for item in seq:
       marker = idfun(item)
       # in old Python versions:
       # if seen.has_key(marker)
       # but in new ones:
       if marker in seen: continue
       seen[marker] = 1
       result.append(item)
   return result

def f6(seq):
   # Not order preserving    
   set = Set(seq)
   return list(set)

基准测试结果

* f2 13.24
* f4 11.73
* f5 0.37
f1 0.18
f3 0.17
f6 0.19

答案 1 :(得分:-3)

专门使用您的代码

 l1 = [1,1,2,2,3]
 l2 = [2,1,3,3,4]
 unique=set(l1+l2)

如果您希望将其作为列表而非集合

unique=list(set(l1+l2))