列表理解:如果x已经不在列表中,则将x插入列表中?

时间:2018-03-10 03:39:53

标签: python list list-comprehension

在Python 3中,有没有办法进行列表理解,如果某个对象x已经不在同一个列表中,它会被插入到列表中。我基本上希望代码执行此操作:

my_list = ["aa", "aa", "bb", "bb"]
new_list = [c for c in my_list if c not in new_list]  ## Add each c from my_list into new_list if c is not already in new_list. 

我不想删除my_list中的重复项,我严格需要列表理解技术。有什么方法可以做到这一点吗?

3 个答案:

答案 0 :(得分:2)

这是实现这一目标的极其低效的方法:

>>> [x for i, x in enumerate(my_list) if x not in my_list[:i]]
['aa', 'bb']

它的O(N ^ 2)时间和O(N)空间。

不要使用它。写好的代码

同样效率低下的解决方案:

>>> [x for i, x in enumerate(my_list) if my_list.index(x) == i]
['aa', 'bb']

答案 1 :(得分:-1)

O(N)空间和O(N)时间使用辅助集:

seen = set()
[seen.add(x) or x for x in my_list if x not in seen]

返回

['aa', 'bb']

答案 2 :(得分:-1)

您可以在一行中以多种方式执行此操作而无需修改原始列表。以下是一些方法:

使用列表理解:

my_list = ["aa", "aa", "bb", "bb"]
new_list=[]
[new_list.append(i) for i in my_list if i not in new_list]

使用set:

my_list = ["aa", "aa", "bb", "bb"]
print(list(set(my_list)))

使用itertools:

import itertools
print(list(map(lambda x:x[0],itertools.groupby(my_list))))

使用集合:

import collections
print(collections.Counter(my_list).keys())

使用dict.fromkeys():

print(list(dict.fromkeys(my_list)))