使用a = list(set(a))
a= [2, 3, 4, 5, 7]
不光删除了重复元素,还进行了排序
![小技巧:去掉List和Strings中重复的元素并排序 - 牛皮糖 - 牛皮糖的旅程 小技巧:去掉List和Strings中重复的元素并排序 - 牛皮糖 - 牛皮糖的旅程](http://img20.ph.126.net/MOYOjhpKO71sP7DherXk6w==/3156741863812214135.jpg)
再来看看字符串吧,同样删除了重复元素,并进行了排序
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
请看官网的说明:
Sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
新增:刚看来的,如果只想删去重复元素,要保持列表的序列的话,可以这么做
-
# to keep the order use a modified list comprehension
-
mylist = [2, 34, 5, 5, 6, 6, 7, 2]
-
ulist = []
-
[ulist.append(x) for x in mylist if x not in ulist]
-
print ulist # [2, 34, 5, 6, 7]