zoukankan      html  css  js  c++  java
  • 小技巧:去掉List和Strings中重复的元素并排序

    给出a = [3, 3, 5, 7, 7, 5, 4, 2]
    使用a = list(set(a)) 

    a= [2, 3, 4, 5, 7]

    不光删除了重复元素,还进行了排序

    小技巧:去掉List和Strings中重复的元素并排序 - 牛皮糖 - 牛皮糖的旅程
     
    再来看看字符串吧,同样删除了重复元素,并进行了排序
    >>> 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]
    None
  • 相关阅读:
    PyQuery
    计算 1+1/2!+1/3!+1/4!+...1/20!=?
    计算5的阶乘 5!的结果是?
    一张纸的厚度大约是0.08mm,对折多少次之后能达到珠穆朗玛峰的高度(8848.13米)?
    百马百担
    九九乘法表
    百钱买百鸡
    三角形菱形
    水仙花
    前缀表达式的计算
  • 原文地址:https://www.cnblogs.com/yuxc/p/2029767.html
Copyright © 2011-2022 走看看