Tuesday, July 10, 2018

python - How to delete duplicate values in a list?





Possible Duplicate:
How do you remove duplicates from a list in Python whilst preserving order?






Let us consider the list:




x = ['a', 'b', 'c', 'c', 'a', 'd', 'z', 'z']


I want to delete these duplicate values list-x and want the result as:



y = ['a', 'b', 'c', 'd', 'z']

Answer



If ordering doesn't matter, use a set:




>>> list(set(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']))
['a', 'p', 'c', 'b', 'd']


If ordering does matter, use an OrderedDict:



>>> from collections import OrderedDict 
>>> OrderedDict.fromkeys(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']).keys()
['a', 'b', 'c', 'd', 'p']


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...