The best way to get unique elements of a list in Python

The best way to get unique elements of a list in Python

Inspired by the Book Machine Learning in Action

最近在学习和实现 Machine Learning in Action 这本书的时候,在Chapter 3 看到了一个非常有趣的结论:

从列表中创建集合是Python语言得到列表中唯一元素的最快方法。

也就是说,要从一个list中不重复地得到它所有的元素,最好的方法是用内置函数 set 来将这个 list 变为一个元组。

For example:

>>> l = list([‘a’,’b’,’c’,’a’,’a’,’c’,’b’,’b’])
>>> l
[‘a’, ‘b’, ‘c’, ‘a’, ‘a’, ‘c’, ‘b’, ‘b’]
>>> elements = set(l)
>>> elements
set([‘a’, ‘c’, ‘b’])

也是非常有意思!

你可能感兴趣的:(python,机器学习,语言,【Python,笔记】)