给出a = [3, 3, 5, 7, 7, 5, 4, 2]
使用a = list(set(a))
a= [2, 3, 4, 5, 7]
不光删除了重复元素,还进行了排序
再来看看字符串吧,同样删除了重复元素,并进行了排序
>>> 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]
本文介绍了Python中如何使用集合(set)去除列表(list)中的重复元素,并保持原有的顺序。通过实例展示了集合的基本操作如并集、交集等,并提供了一种有效的方法来创建不包含重复项的有序列表。
1641

被折叠的 条评论
为什么被折叠?



