• Python 进阶技能:列表、字典、集合的处理


    来自B站

    在列表,字典,集合中根据条件筛选数据

    示例:

     1 from random import randint
     2 
     3 # 根据条件筛选数据
     4 
     5 lst = [23,56,67,89,0,98,45,67,46,65]
     6 
     7 # 列表解析  -- 推荐
     8 new_lst1 = [n for n in lst if n >= 60]
     9 print(new_lst1)
    10 
    11 # filter()函数解析
    12 new_lst2 = filter(lambda x: x >=60 , lst)
    13 print(list(new_lst2))
    14 
    15 # 用字典解析创建数据
    16 dic = {'Student%d' % i: randint(0,100) for i in range(1,20)}
    17 print(dic)
    18 
    19 # 字典解析筛选数据 - 推荐
    20 new_dict1 = {k:v for k,v in dic.items() if v >= 60}
    21 print(new_dict1)
    22 
    23 # filter()函数解析字典
    24 new_dict2 = filter(lambda item: item[1] >= 60, dic.items())
    25 print(dict(new_dict2))
    26 
    27 # 集合解析 - 推荐
    28 s = {randint(0,20) for _ in range(20)}
    29 new_s = {x for x in s if x % 3 == 0}
    30 print(new_s)

    为元组中的每个元素命令,提高程序可读性。元组比其他类型的优点:节省空间

    示例:

     1 # 方法1: 枚举
     2 from enum import IntEnum
     3 
     4 s = ('Su',12,'male','123@qq.com')
     5 
     6 class StudentEnum(IntEnum):
     7     NAME = 0
     8     AGE = 1
     9     SEX = 2
    10     EMAIL = 3
    11 
    12 print(s[StudentEnum.NAME])    # 输出 Su
    13 print(s[StudentEnum.AGE])     # 输出 12
    14 
    15 
    16 # 方法2: 使用标准库中collections.nametuple 替代内置tuple  - 推荐
    17 from collections import namedtuple
    18 Student = namedtuple('Student',['name','age','sex','email'])
    19 s2 = Student('Su',12,'male','123@qq.com')
    20 print(s2)     # 输出 Student(name='Su', age=12, sex='male', email='123@qq.com')
    21 print(s2[1])    # 输出 12
    22 print(s2.age)   # 输出 12

    根据字典中值的大小,对字典中的项排序

    示例

     1 # 将字典中的各项转换成元组,使用内置函数sorted排序
     2 
     3 # 方法1:将字典中的项转化为(值,键)元组。(列表解析或zip)
     4 from random import randint
     5 
     6 old_dict = {k: randint(0,100) for k in 'abcdefghijkl'}
     7 print(old_dict)   # 输出字典
     8 # 列表解析 转成元组
     9 dict_to_tuple = [(v,k) for k,v in old_dict.items()]
    10 # zip函数 转成元组
    11 # dict_to_tuple = list(zip(old_dict.values(),old_dict.keys()))
    12 print(dict_to_tuple)   # 输出列表,元素是元组
    13 print(sorted(dict_to_tuple))   # 升序  输出列表,元素是元组
    14 print(sorted(dict_to_tuple,reverse=True))  # 倒序   输出列表,元素是元组
    15 
    16 # 方法2:传递sorted函数的key参数
    17 p = sorted(old_dict.items(),key=lambda item: item[1],reverse=True)
    18 print(p)   # 倒序   输出列表,元素是元组,key在前 value在后的元组
    19 p_num = list(enumerate(p,1))   # 第2个参数1是指从1开始算
    20 print(p_num)   # 输出 [(1, ('i', 94)), (2, ('l', 81)), (3, ('g', 80))。。。。=》 顺序,(key, value)
    21 d = {k:v for i, (k,v) in p_num}
    22 print(d)   #输出倒序的字典

    统计序列中元素的频度

    示例:对数字进行统计,并取最大前几位

     1 from random import randint
     2 
     3 data = [randint(0,5) for _ in range(10)]
     4 print(data)
     5 
     6 # 方法1:将序列转换为字典{元素:频度},根据字典中的值排序
     7 d = dict.fromkeys(data,0)   # data列表的元素作key,0为设置的value
     8 print(d)
     9 
    10 for x in data:
    11     d[x] += 1   # 循环列表,元素每出现一次,累加一次到字典上
    12 print(d)
    13 
    14 # 以value作排序,取最高前三个
    15 # res = sorted([(v,k) for k,v in d.items()], reverse=True)[:3]   # 列表解析
    16 res = sorted(((v,k) for k,v in d.items()), reverse=True)[:3]   # 生成解析,比列表解析更节省空间
    17 print(res)
    18 
    19 # 当列表数据量很大,但只查出现次数最大的几个时,上面这种方法就有缺点了:浪费
    20 # 推荐heapq模块方法查找最大几个或最小几个元素
    21 import heapq
    22 res = heapq.nlargest(3, ((v,k) for k,v in d.items()))
    23 print(res)
    24 
    25 # 方法2:使用标准库collections中的Counter对象。  ---   推荐
    26 from collections import Counter
    27 c = Counter(data)
    28 res = c.most_common(3)   # 查找前三个
    29 print(res)

    示例:对文件内容字符串出现的次数作统计

     1 import re
     2 from collections import Counter
     3 
     4 # 读取文件
     5 with open('1.txt','r') as f:
     6     allData = f.read()   # 读出str类型
     7 
     8 world_lst = re.split('\s+',allData)  # 空格、换行...进行分割
     9 c = Counter(world_lst)
    10 res = c.most_common(5)   # 字符串出现次数最高的前5个
    11 print(res)

    在多个字典中寻找公共键

    示例:方法1,和方法3都可用

     1 from random import randint
     2 
     3 dict1 = {k:randint(0,5) for k in 'ABCDEFG'}
     4 dict2 = {k:randint(0,5) for k in 'ABCFG'}
     5 dict3 = {k:randint(0,5) for k in 'ABCDE'}
     6 dict4 = {k:randint(0,5) for k in 'ACDEFG'}
     7 all_dict = [dict1, dict2, dict3, dict4]
     8 
     9 # 方法1
    10 res = [k for k in all_dict[0] if all(map(lambda d: k in d, all_dict[1:]))]
    11 print(res)
    12 
    13 
    14 from functools import reduce
    15 # 利用集合(set)的交集操作
    16 
    17 # 方法2
    18 # 使用字典的key()方法,得到一个字典keys的集合
    19 s1 = dict1.keys()
    20 s2 = dict2.keys()
    21 s3 = dict3.keys()
    22 s4 = dict4.keys()
    23 print(s1 & s2 & s3 & s4)   # 如果有很多字典,这方法就太繁琐了
    24 # 使用map函数,得到每个字典keys的集合
    25 s = list(map(dict.keys,all_dict))   # 得到的是每个字典的key,未集合
    26 print(s)
    27 
    28 # 方法3
    29 # 使用reduce函数,取所有字典的keys集合的交集
    30 res = reduce(lambda a, b: a & b, map(dict.keys,all_dict))  # 得到每个字典key交集
    31 print(res)

    让字典保持有序

    示例:OrderedDict()函数,按写入顺序排序的字典;查找key在字典的位置;字典某些位置的成员key是什么

     1 from collections import OrderedDict
     2 
     3 od = OrderedDict()  #一个字典,自动按照写入顺序排序
     4 # od['s'] = 2
     5 # od['w'] = 1
     6 # od['p'] = 7
     7 # print(od.keys())
     8 
     9 from random import shuffle
    10 players = list('abcdefg')
    11 shuffle(players)    # 打乱列表顺序
    12 print(players)
    13 
    14 for i, p in enumerate(players, 1):  # 从1开始,给players元素带个数字
    15     od[p] = i
    16 print(od)
    17 
    18 def query_by_name(d,name):   # 某个key在字典的第几个成员
    19     return d[name]
    20 
    21 print(query_by_name(od,'c'))
    22 
    23 from itertools import islice
    24 
    25 def query_by_position(d,start_position, end_position=None):
    26     start_position -= 1
    27     if end_position is None:
    28         end_position = start_position + 1
    29     return list(islice(d, start_position, end_position))
    30 
    31 print(query_by_position(od, 3))     # 字典第3个成员key是
    32 print(query_by_position(od, 3, 6))    # 字典第3~6的成员key是

    用户的历史记录功能(最多n条)

    示例:保存在磁盘;保存在本地

     1 from collections import deque
     2 
     3 # deque() 双端队列
     4 dq = deque([], 5)  # 第一个参数是队列初始化,参数5是容量,不填则容量无限大
     5 # dq.appendleft()  # 左端入队, 要保持同端入队
     6 dq.append(2)  # 右端入队
     7 dq.append(3)
     8 dq.append(4)
     9 dq.append(5)
    10 dq.append(1)
    11 dq.append(6)
    12 print(list(dq))   # 输出[3, 4, 5, 1, 6]。当容量满了时,继续入队,则最开始入队的就会从左端出队
    13 
    14 # 上面的存入是在磁盘中,以下为保存在本地文件
    15 import pickle
    16 
    17 pickle.dump(dq, open('saveLocal.pkl', 'wb'))   # 二进制,写入
    18 res = pickle.load(open('saveLocal.pkl', 'rb'))   # 读取
    19 print(res)
  • 相关阅读:
    Microsoft Biztalk Server 2000简介
    BizTalk学习笔记系列之二:实例说明如何使用BizTalk
    BizTalk学习笔记系列之三:企业集成应用和BizTalk
    简单状态机Workflow基于Web应用【转】
    C#类、接口、虚方法和抽象方法
    多表查询语句写法、数据库数字如何转化为汉子、Sql语句拼接
    IsPostBack用法
    Net前台页面如何调用后台cs变量
    aspx页面中写if else 语句的方法,
    查询数据库最大的索引、静态类与非静态类的区别、后台操作DIV样式的方法、C#操作TreeView组件中的一些常用方法及具体实现
  • 原文地址:https://www.cnblogs.com/sue2015/p/15987564.html
Copyright © 2020-2023  润新知