• python编程技巧


    #  0 如何为元组中的每个元素命名,并提高程序的可读性
    
    name,age = range(2)  # 这样 name=0,age=1
    
    t = ('andy','12')
    
    t[name]  # 按照索引取出的是‘andy’
    
    # 还有一种方式,按照属性取值
    
    from collections import namedtuple
    
    Student = namedtuple('Student',[''name,'age','sex','email'])
    
    s = Student('andy','12','man','1111@qq.com')
    
    s.name  # 取值,按照属性
    
    
    
    #1 随机序列[1,2,4,5,6,2,1,3,423,44,2...]中,找出出现次数最高的三个元素,他们出现的次数是多少
    from random import randint
    data = [randint(1,20) for x in range(30)]
    c = dict.fromkeys(data,0)
    for i in data:
        c[i]+=1
    
    # 2使用collections来快速找出
    from collections import Counter
    c2 = Counter(data)
    c2.most_common(3)  # 找出出现最多的key
    
    # 3 使用re对对英文文章进行词频统计
    import re
    from collections import Counter
    data = open('test.txt').read()
    c3 = Counter(re.split('/W+',data))
    c3.most_common(4)  # 统计出出现频率最高的4个单词
    
    # 4 对字典里面的值根据value排序
    from random import randint
    d = {i:randint(60,100) for i in 'abcdef'}
    data = sorted(d.items(),key = lamdba x: x[1])

    二:快速找到字典中的公共键

    from random ranint,sample  # sample是随机取样,就是在一堆数据中随机取几个

    sample('abcdefg',3)  # 在对象中随机取三个并生成一个列表

    sample('abcdefg',randint(3,6))  # 生成3到6个之间随机的列表

    s = {x: randint(1,5)  for x in sample('abcdefg',randint(3,6))}  # 生成一个随机的字典

  • 相关阅读:
    python中的函数编程
    Python中的类型关系和继承关系
    MySQLdb for Python使用指南
    调试模式
    js window.open打开新页面
    JVM调优
    jacoco(spring boot启动) agent tcpserver使用方案
    C#多线程之ManualResetEvent和AutoResetEvent
    下载verycd的方法下载电驴资源隐藏资源的最新可用方法
    C# 多线程之信号量Semaphore
  • 原文地址:https://www.cnblogs.com/ouyang99-/p/12142958.html
Copyright © 2020-2023  润新知