zoukankan      html  css  js  c++  java
  • Python中一些高效的数据操作

    1. 列表统计
    chars = ["a", "b", "a", "c", "a", "d"]
    

    使用count获取单个字符出现次数

    chars.count("a")
    

    使用Counter的most_commom获取 出现次数最多的前几位

    from collections import Counter
    print(Counter(chars).most_common(2)
    
    1. 字典键值的集合操作

    字典的keys()支持 并集| 交集 & 差集- 等集合操作

    dict_a = {"a": 1, "b": 2, "c": 3 }
    dict_b = {"a": 1, "c":2, "d": 4}
    
    dict_a.keys() & dict_b.keys()
    

    当字典的values都是字符串(无嵌套)时,字典的items()也支持集合操作
    断言字典a包含字典b

    assertFalse(dict_b.items() - dict_b.items())
    
    1. 列表嵌套字典操作
    fruits = [{"name": "apple", "price": 4},
    {"name": "orange", "price": 5}, {"name": "pear", "price":6} ,{"name": "apple", "price": 5}]
    

    排序

    sorted(fruits, key=lambda x: x["price"])
    

    可以使用itemgetter代替lambda表达式
    from operator import itemgetter
    sorted(fruits, itemgetter("price"))

    最小

    mim(fruits, key=lambda x: x["price"])
    

    最大

    max(fruits, key=lambda x: x["price"])
    

    使用堆获取最大/最小的前几个

    import heapq
    heapq.nlargest(2, fruits, key=lambda x: x["price"])
    heapq.nsmallest(2, fruits, key=lambda x: x["price"]
    

    分组groupby

    from itertools import groupby
    groups = groupby(fruits, key=lambda x:x["name"])
    
    for name, fruits in groups:
        print(name, len(list(fruits)))
    

    更多学习资料请加添加作者微信:lockingfree获取

  • 相关阅读:
    Java集合 使用Map
    Java集合 编写equals方法
    yiyou本地安装出现版本问题
    网站地图制作
    SEO小爬虫工具文章排版
    知名企业招聘技术员题库
    测试上网速度
    邮件传输协议软件
    JSONP跨域问题
    织梦搬家
  • 原文地址:https://www.cnblogs.com/superhin/p/11454971.html
Copyright © 2011-2022 走看看