`
scm002
  • 浏览: 309275 次
社区版块
存档分类
最新评论

小技巧:去掉List和Strings中重复的元素并排序

 
阅读更多

给出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.
新增:刚看来的,如果只想删去重复元素,要保持列表的序列的话,可以这么做
  1. # to keep the order use a modified list comprehension
  2. mylist = [2, 34, 5, 5, 6, 6, 7, 2]
  3. ulist = []
  4. [ulist.append(x) for x in mylist if x not in ulist]
  5. print ulist # [2, 34, 5, 6, 7]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics