python_生成器小结

#__author : "ziChuan"
#__data : 2019/7/19
import random
# print(random.random())
# print(random.randint(1,8))  #包含8
#print(random.choice("hello"))
#print(random.choice([[1,2,3],2,"1234"]))
#print(help(random.shuffle))
#print(random.sample([[1,2,3],2,"1234"],2))
#print(random.randrange(1,4))

#做个练习:不完整验证码
def v_code(): code = "" for i in range(5): add_num = random.choice([random.randrange(10), chr(random.randrange(65, 91))]) #if i == random.randint(0,4): # if random.choice: # add_num = random.randrange(10) # else: # add_num = chr(random.randrange(65,91)) code += str(add_num) print(code) v_code()

#列表生成器

[x*2 for x in range(10)]

 

#生成器(generator object)

  

创建生成器的两种方式:

    1、(x*2 for x in range[10]) >>>>>>>>>>>>>>generator object
    2、def f():
        print("ok")
        yield 2
        print("ok")
        f() >>>>>>>>>>>>>>>>>>>>>>generator object

    生成器的方法:
      1、next(f()) ------------------------------------计算出一个值
        注意:生成器在创建的时候已经决定了能计算出值的个数,调用
          next的次数超过这个值就会报StopIteration
        遍历所有元素可以使用for循环:
            for i in [1,2,3]:
              print i
          for循环内部做了三件事:
            1、调用对象的iter()方法,返回一个迭代器对象
            2、while:
                try:
                  i = next(list_Iterator)
                except StopIteration:
                  break
      2、send():
          f().send(None) #等价于next(f())

#迭代器

#满足迭代器协议:
  1、内部有next方法
  2、内部有Iter()方法

  li = [1,2,3]:Iterable(内部有Iter方法) >>>>>>>>>>>>>>iter()
  i = iter(li):list_Iterator
 

#模块

import time  #时间模块 
  time.time  #时间戳
  time.strftime()  #格式化时间戳
  time.gmtime() #UTC 时间
  time.localtime #北京时间
  time.ctime()  #时间日期格式
datetime
  datetime.datetime.now()
  
import random #随机数模块
  chr()  #将数字转化为字母 验证码

 

 

          

posted @ 2019-07-19 09:23  MTcx  阅读(122)  评论(0编辑  收藏  举报