简体   繁体   English

在Python列表中删除重复的项目

[英]Remove repeated item in list in python

Let say I have a list of 假设我有一个清单

['a','man', 'and', 'a', 'woman']

How do I remove the repeated 'a' so that it will only be: 如何删除重复的“ a”,使其仅是:

['a','man', 'and', 'woman']

Keeps order: 保持秩序:

>>> from collections import OrderedDict
>>> L = ['a','man', 'and', 'a', 'woman']
>>> list(OrderedDict.fromkeys(L))
['a', 'man', 'and', 'woman']

If the order is not important, then you can just do: 如果顺序不重要,则可以执行以下操作:

d = ['a', 'man', 'and', 'a', 'woman']
list(set(d))

如果顺序很重要,类似@ jamylak的一个建议,就是用这个 OrderedSet配方。

list(OrderedSet(L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM