美文网首页
python列表,字典排序使用小知识点

python列表,字典排序使用小知识点

作者: Python数据分析实战 | 来源:发表于2018-08-18 15:58 被阅读84次
    将数字列表,转为字符串
    # (low, height, 多少位) # 随机生成3个元素的1~10的列表
    a = np.random.randint(1, 10, 3)
    # [1 7 1]
    
    arr = map(str, a)
    # <class 'map'>  可遍历, 但只能使用一次
    
    # 将字符列表 拼接为字符串
    b = ''.join(arr)
    # 171
    
    print(b)
    
    列表中有重复元素的各种处理
    1、找到一个列表中的重复元素
    # 利用里  列表.count(元素)  该元素出现的次数
    a = ['l', 'i', 'u', 'h', 'a', 'i', 'w', 'l', 'n']
    ret= [val for val in list(set(a)) if a.count(val) >= 2]
    print(ret)  
    # ['l', 'i']
    
    2、找到一个列表中的元素出现的次数
    from collections import Counter
    
    alist = [1,2,2,2,2,3,3,3,4,4,4,4]
    ret = Counter(alist)
    # Counter({2: 4, 4: 4, 3: 3, 1: 1})
    
    # 求得不重复元素的个数
    count = len(set(alist))
    
    # 与列表嵌套元组的形式展示元素即个数
    result = ret.most_common(count)
    print(result)
    # [(2, 4), (4, 4), (3, 3), (1, 1)]
    
    3、列表删除重复元素,顺序保持不变
    l1 = ['b', 'c', 'd', 'b', 'c', 'a', 'a']
    
    #l2 = list(set(l1))
    #l2.sort(key=l1.index)
    l2 = sorted(set(l1), key=l1.index)
    
    print (l2)
    ['b', 'c', 'd', 'a']
    
    # 集合是无须的,不能保证元素的顺序
    print(list(set(l1)))
     ['b', 'd', 'c', 'a']
    
    给定两个 list A ,B,请用找出 A ,B 中相同的元素,A ,B 中不同的元素
    A、B 中相同元素: set(A)&set(B)
    A、B 中不同元素: set(A)^set(B) 
    A、B 中总同=共元素: set(A) | set(B)
    A、B 中 A有B没有的元素:A - B
    
    列表排序
    my_list = [[1, 4, 8], [1, 3, 6], [6, 4, 9]]
    
    # 按下标位置排序
    my_list.sort(key=lambda temp:temp[2])
    print(my_list)
    # [[1, 3, 6], [1, 4, 8], [6, 4, 9]]
    
    字典排序

    object.sort(key=lambda temp:temp[0])
    temp:表示其中的一个元素 排序的标准是 temp:后面的值

    1、纯字典排序
    dict = {'a':3, 'c':5, 'b':2}
    
    # 0:按字典的key排序  1:按value排序
    result = sorted(dict.items(), key=lambda temp:temp[0])
    print(result)
    
    2、字典列表--key相同
    dict2 = [{'name':'lily', 'age':21}, {'name':'jack', 'age':25}, {'name':'tom', 'age':18}]
    
    # 按指定的字典的key排序
    dict2.sort(key=lambda temp:temp['name'])
    print(dict2)
    # [{'name': 'jack', 'age': 25}, {'name': 'lily', 'age': 21}, {'name': 'tom', 'age': 18}]
    
    3、字典列表--key不同
    alist = [{"a": 3}, {"c": 6}, {"b": 2}]
    
    # 按key排序
    alist.sort(key=lambda temp:list(temp.keys())[0])
    print(alist)
    # [{'a': 3}, {'b': 2}, {'c': 6}]
    
    # 按value排序
    alist.sort(key=lambda temp:temp[list(temp.keys())[0]])
    print(alist)
    # [{'b': 2}, {'a': 3}, {'c': 6}]
    

    python的一个内置函数:
    ord() : 参数为长度为1的字符串
    返回对应的 ASCII 数值,或者 Unicode 数值

    num = ord('a')
    print(num) # 97

    相关文章

      网友评论

          本文标题:python列表,字典排序使用小知识点

          本文链接:https://www.haomeiwen.com/subject/rnqfiftx.html