Python基础中一些高效的数据操作,可以提高你十倍工作效率
生活随笔
收集整理的這篇文章主要介紹了
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)2.字典鍵值的集合操作
字典的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
3.列表嵌套字典操作
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"])使用堆獲取最大/最小的前幾個
''' 學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' 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)))總結
以上是生活随笔為你收集整理的Python基础中一些高效的数据操作,可以提高你十倍工作效率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础入门:使用openpyx
- 下一篇: python基础入门:实现(无重复字符)