zoukankan      html  css  js  c++  java
  • 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))}  # 生成一个随机的字典

  • 相关阅读:
    Recommender Systems 基于知识的推荐
    粒子群优化算法简介
    彻底弄懂LSH之simHash算法
    c++ 字符串函数用法举例
    Linux上的运行的jar包
    推荐系统判定标准
    python 细枝末节
    PV UV
    python解析json
    生成n对括号的所有合法排列
  • 原文地址:https://www.cnblogs.com/ouyang99-/p/12142958.html
Copyright © 2011-2022 走看看