python eval() iter() next() 等 function

  • eval() function 将字符串转化为 python 可运行的表达式 https://www.jianshu.com/p/753aba694cf5
    Definition: eval(source: Union[Text, bytes, CodeType], globals: Optional[Dict[str, Any]]=..., locals: Optional[Mapping[str, Any]]=..., /) -> Any
    Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.

def a():
    print('a')
eval('a') # <function __main__.a()>
eval('a')() # 'a'

DIEN/process_data.py use eval() to convert string "{1:1,2:2}" to dict

  • iter() 和 next() function 常用python 类中,用于构造一个可以迭代的数据类

https://www.jb51.net/article/149090.htm
list、tuple等都是可迭代对象,我们可以通过 iter() 函数获取这些可迭代对象的迭代器。然后我们可以对获取到的迭代器不断使⽤next()函数来获取下⼀条数据。iter()函数实际上就是调⽤了可迭代对象的 iter ⽅法。

>>> li = [11, 22, 33, 44, 55]
>>> li_iter = iter(li)
>>> next(li_iter) 11
>>> next(li_iter) 22
>>> next(li_iter) 33
>>> next(li_iter) 44
>>> next(li_iter) 55
>>> next(li_iter)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>

注意:当我们已经迭代完最后⼀个数据之后,再次调⽤next()函数会抛出 StopIteration的异常,来告诉我们所有数据都已迭代完成,不⽤再执⾏ next()函数了。在深度学习的多轮训练中,可以使用 try ... except 来捕获异常,重新再从头过一轮数据进行训练。

posted @ 2020-07-02 10:41  Gelthin  阅读(321)  评论(0编辑  收藏  举报