复习+学习:type函数、生成器函数、zip函数、dict函数及yield

在看《编写高质量的代码 改善python 程序的91个建议》,“建议11:理解枚举替代实现的缺陷”,遇到如下代码:

def enum(*posarg, **keysarg):
	return type("Enum", (object,), dict(zip(posarg, xrange(len(posarg))), **keysarg))

对我这个python入门级选手,这段代码正好可以利用来复习以下知识:
. type函数
. zip函数
. * 和 **
. dict函数
. 生成器
也可以学习下面的新知识
. 如何自定义生成器函数
. yield函数


下面进入正题:

  • type 函数

    	class type(name, bases, dict)
    
    • 当只有第一个参数时,type函数用户返回该对象的类型。可以利用type函数来查询一个对象的类型。
    • 当提供第二、三个参数时,type函数返回一个新类型。
      参考对元类的理解:2019新年快乐 - 学习python的“元类”
      • name: 类的名称
      • bases: 基类的元组
      • dict: 字典,类内定义的命名空间变量
  • zip函数:

    • 定义:zip([iterable, …]),接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些 tuples组成的list(列表)。
    • 返回:返回一个zip对象,其内部元素为元组;可以转化为列表或元组;
    • 传入参数: 元组、列表、字典等迭代器。
  • *zip函数:zip函数的“逆向操作”,直白一些理解的话,可以这么解释*zip函数:

    • 首先,看作是一个zip函数,得到一个列表对象;
    • 然后,通过*操作符(拆包操作),将zip函数返回的列表对象的各“分量元素”解包成独立的可迭代对象。
  • * 和 **

    • *表示从紧随其后的迭代器中取出相应的“位置参数”
    • **表示所有未捕获的“关键字参数”,都将被存储在紧随其后的字典对象中。
  • dict函数:创建字典

    • class dict(**kwarg) #通过传入的关键字实参创建字典,如(a=‘a’, b=‘b’, c=‘c’);
    • class dict(mapping, **kwarg) # 从映射对象(键, 值对)创建(关键字实参可选);
    • class dict(iterable, **kwarg) # 从至少有两个元素的可迭代对象创建(关键字实参可选。
    • 仔细阅读构造器dict的定义:

1英文原文来自:python.org
中文是我自己翻译的


Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
返回一个新的字典,这个字典对象由可选的位置实参初始化而成,也可以由一系列关键字实参初始化而成(关键字实参可以为空)。

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
如果没提供位置实参,就产生一个空的字典,如果提供的位置实参是映射对象,就产生一个和该映射对象的“键-值对”相同的字典。除了上述两种位置实参的类型,其它位置实参的类型必须是“可迭代对象”,可迭代对象中的每个元素自身也必须是可迭代的,并且有且只能有两个对象,其中的第一个对象作为新字典的键,第二个对象是该键的值。如果键出现多次,则最后一个和键对应的值是新字典里该键的值。

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
如果提供了关键字实参,关键字实参所对应的键值会被添加到位置实参建立的新字典的后面,如果键已经存在,关键字实参中的值会替代位置实参中的值。


  • 如何自定义生成器函数:定义一个有迭代器行为的函数。
    • 利用yield函数,生成器函数与普通函数的区别是生成器返回的是一个迭代器对象,只有next()或send()方法能够使生成器运行,像函数一样调用生成器并不会直接运行,只会返回一个生成器对象。
    • 在调用生成器函数的过程中,每次遇到yield,函数会暂停并保存当前所有运行信息,返回yield后面的值,并在下次执行next()或send()方法时从当前位置继续运行,直到遇到下一个yield或者满足结束条件并结束函数为止。

以杨辉三角形为例:

def triangle():
    _list, new_list = [], []
    while True:
        length = len(_list)
        if length == 0:
            new_list.append(1)
        else:
            for times in range(length + 1):
                if times == 0:
                    new_list.append(1)
                elif times == length:
                    new_list.append(1)
                else:
                    temp = _list[times - 1] + _list[times]
                    new_list.append(temp)
        yield new_list #返回值,然后挂起函数,等待下一次调用
        _list = new_list.copy()#调用后会继续执行下去
        new_list.clear()

n = 0
for result in triangle():
    n += 1
    print(result)
    if n == 10:
        break

  1. Mapping Types — dict ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

steventian72

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值