Jos*_*hua 3 python list duplicates
我试图使用以下代码从列表中删除重复项:
a = [1,2,3,4,2,6,1,1,5,2]
res = []
[res.append(i) for i in a if i not in res]
Run Code Online (Sandbox Code Playgroud)
但是我想这样做而不将我想要的列表定义为一个空列表(即省略该行res = []),例如:
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
Run Code Online (Sandbox Code Playgroud)
我想避免图书馆进口和 set()
小智 6
我认为可能对你有用。它在保持顺序的同时从列表中删除重复项。
newlist=[i for n,i in enumerate(L) if i not in L[:n]]
Run Code Online (Sandbox Code Playgroud)
对于 Python3.6+,您可以使用dict.fromkeys():
>>> a = [1, 2, 3, 4, 2, 6, 1, 1, 5, 2]
>>> list(dict.fromkeys(a))
[1, 2, 3, 4, 6, 5]
Run Code Online (Sandbox Code Playgroud)
从文档:
使用可迭代的键和设置为值的值创建一个新字典。
如果您使用的是较低的 Python 版本,则需要使用collections.OrderedDict以下命令来维护顺序:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |