I was trying to remove duplicates from a list using the following code:
a = [1,2,3,4,2,6,1,1,5,2]
res = []
[res.append(i) for i in a if i not in res]
But I would like to do this without defining the list I want as an empty list (ie, omit the line res = []) like:
a = [1,2,3,4,2,6,1,1,5,2]
#Either:
res = [i for i in a if i not in res]
#Or:
[i for i in a if i not in 'this list'] # this list is not a string. I meant it as the list being comprehensed
I want to avoid library imports and set()
解决方案
For Python3.6+, you can use dict.fromkeys():
>>> a = [1, 2, 3, 4, 2, 6, 1, 1, 5, 2]
>>> list(dict.fromkeys(a))
[1, 2, 3, 4, 6, 5]
From the docs:
Create a new dictionary with keys from iterable and values set to value.
If you are using a lower Python version, you will need to use collections.OrderedDict to maintain order:
>>> from collections import OrderedDict
>>> a = [1, 2, 3, 4, 2, 6, 1, 1, 5, 2]
>>> list(OrderedDict.fromkeys(a))
[1, 2, 3, 4, 6, 5]