zoukankan      html  css  js  c++  java
  • python基础 常见用法

    1、python计时器timeit模块

      1)timeit 模块定义了接收两个参数的Timer类,两个参数都是字符串。

        参数1:要计时的语句或者函数

        参数2:为参数1构建环境的导入语句

      2)Timer对象主要有两个方法:

        timeit(n):接收一个参数,表示每次计时时,执行被计时语句的次数,返回值为秒,默认100万次。

        repeat(n1,n2):接收两个参数,返回每次测试的耗时列表,单位为秒。

          参数1:重复整个测试的次数,默认为3

          参数2:每次测试中,调用被计时语句的次数,默认是100万次

    2、根据条件从列表中过滤数据:过滤大于0的元素

      from random import randint

      data = [randint(-10,10) for x in range(10)]

      思路:

        1)遍历过滤

          res1 = []

          for x in data:

            if x>=0:

              res1.append(x)

        2)列表过滤

          res2 = [x for x in data if x>=0]

        3)使用filter函数过滤

          res3 = list(filter(lambda x :x>=0, data))

    3、根据字典值筛选出符合条件的元素:筛选出分数大于90的学生

      student = {x:randint(60,100) for x in "abcdefg"}

      res = {k:v for k,v in student.items() if v>=90}

    4、筛选出集合中能够被3整除的元素

      data = set(randint(0,20) for x in range(10))

      res = {x for x in data if x%3==0}

    5、解决只能通过下标访问元组元素的方法:

      通过标准库中的collections.namedtuple

      namedtuple是一个函数,它的本质上就是创建了一个类对象。并规定了tuple元素的个数,并可以用属性而不是索引来引用tuple元素的个数。

      通常情况下,如果我们要创建一个类对象,是这样做的:

        class Student():

          def __init__(self, name, age, gender, mail):

            self.name = name

            self.age = age

            ...

        然后实例化对象 stu = Student(("john","34","male","1@1.com")

      现在我们可以通过namedtuple来创建这样一个Student对象:

        from collections import namedtuple

        stu = namedtuple("Student",["name", "age","gender", "mail"])

        data = stu("john","34","male","1@1.com")

        data.name = "john"

        namedtuple还支持传入关键字参数或是tuple,list,字典等的方式

        # 传入关键字参数

        data = stu(name="john", age=34, gender='male', mail="1@1.com")

        # 传入tuple

        stu_info = ("john","34","male")

        data = stu(*stu_info, mail='1@1.com')

        # 传入list

        stu_info = ["john","34","male"]

        data = stu(*stu_info, mail='1@1.com')

        # 传入dict

        stu_info = {

          "name":"john",

          "age":34,

          "gender":"male",

        }

        data = stu(**stu_info, mail='1@1.com')

       另外由于namedtuple继承自tuple,所以它也具备tuple的拆分属性

        name, age, *others = data

        print(name, age, others)  #john, 34, ['male', 1@1.com]

    6、排序

      对字典进行排序:

      【sorted(data, key=lambda x:x[1], reverse=True)】

      三个参数:

        1)data:待排序字典

        2)key:排序依据:lambda x:x[1] 根据值进行排序,如果是x[0]是根据key进行排序

        3)reverse:True-->倒序排列,False-->正序排列

      data = [randint(1,10) for x  in range(20)]

      d = dict.fromkeys(data,0)

      for x in data:

        if x in d.keys():

          d[x] += 1

      res = sorted(d.items(), key=lambda x:x[1], reverse=True) # 倒序排列

      res[0],res[1],res[2]

    7、统计一篇文章中出现次数最多的10个单词及其出现的次数

      【使用标准库中的collections.Counter对象】Counter是一个简单的计数器,是dict的一个子类。

         将序列传递给Counter的构造器,得到的是Counter对象是统计过频率的字典

         调用Counter.most_common(n),得到出现次数最多的n个单词

      from collections import Counter

      txt = open(filePath, "r").read()

      import re

      txt_list = re.split("W+", txt)  # 将txt以非字母数字下划线等字符分割

      c = Counter(txt_list)

      c.most_common(10)

      如果有多篇文章需要统计,我们可以分别统计再将统计后的Counter对象合并。如:

      c1 = Counter("hfiehfiabfnjefhef")

      c2 = Counter("fhiofeifoegiefje")

      c2.update(c1)

      print(c2)  # 这里c2就是经过合并后的统计结果了。

       

    8、快速找到多个字典的公共key

      如找到一个班级中所有科目都在90分以上的同学

      解决思路:

        1)使用常规的遍历方式,先遍历某一科90分以上的同学,然后判断该同学是否也在其他90分以上的科目的同学中

        2)使用集合的交集

        3)可以使用python内置的map和reduce搭配使用过滤

          map(function, list)

          reduce(function,list[,initializer])

          map和reduce的区别:map的function接收一个参数;reduce的function接收两个参数

      stu = ["Lilei","Hanmeimei","John","Luly","Lucy","Lily","Lintao","Polly","Fiona"]

      chinese = {s:randint(60,100) for s in stu}

      english = {s:randint(60,100) for s in stu}

      math = {s:randint(60,100) for s in stu}

      chinese_gt90 = {s:c for s,c in chinese.items() if c>=90}

      english_gt90 = {s:c for s,c in english.items() if c>=90}

      math_gt90 = {s:c for s,c in math.items() if c>=90}

      上1):

        res = []

        for s in chinese_gt90.keys():

          if s in english_gt90.keys() and s in math_gt90.keys():

            res.append(s)

      上2):

        chinese_gt90.items() & english_gt90.items() & math_gt90.items()

      上3):

        m = map(dict.keys, [chinese_gt90,english_gt90,math_gt90])

        from functools import reduce

        def red(x,y):

          return x&y

        res = reduce(red,m)

    9、根据用户提交成绩的时间打印成绩排名和姓名及成绩

      需要使用到有序字典OrderedDict,它是按照插入顺序排序,不是key本身排序。

      模拟用户提交系统:

      from collections import OrderedDict

      from time import time

      from random import randint

      start = time()

      total = len(stu)

      d = OrderedDict()

      for i in range(len(stu)):

        input()

        t = time()-start

        name = stu.pop(randint(0,total-1-i))

        d[name] = (i+1, t)

    10、python实现历史记录功能

    解决思路:通过容量为n的队列deque实现,再通过pickle将数据保存到本地文件

    list是线性存储,通过索引访问元素很快,但是要插入或删除数据就很慢了,deque就是为了高效了插入和删除操作的双向列表。deque除了实现了list的append和pop方法外,还支持appendleft和popleft方法,可以高效的往头部添加和删除元素。

    from collections import deque

    from random import randint

    import pickle

    import re

    def guessNum():

      num = randint(60,100)

      d = deque(maxlen = 5)

      print("猜字谜游戏开始,请输入数字...")

      while True:

        inputNum = input()

        if inputNum=="h?":

          print(list(d))

          continue

        if inputNum == ";":

          print("手动结束了游戏")

          with open(file,"wb") as f:

            pickle.dump(list(d), f)

          break

        if not re.match("^d+$",inputNum):

          print("请输入数字")

          continue

        

        inputNum=int(inputNum)

        d.append(inputNum)

        if inputNum<num:

          print("输入的数字太小")

        elif inputNun>num:

          print("输入的数字太大")

        else:

          print("猜对了~")

          with open(file, "wb") as f:

            pickle.dump(list(d), f)

          break

      

  • 相关阅读:
    UGUI血条跟随
    unity组件路径自动生成
    双摄像机使用
    Unity 属性雷达图
    unity UGUI UI跟随
    Unity中实现人物平滑转身
    游戏摇杆
    IIS下载无后缀文件的设置
    convert svn repo to git
    Discovery and auto register
  • 原文地址:https://www.cnblogs.com/fiona-zhong/p/9838926.html
Copyright © 2011-2022 走看看