zoukankan      html  css  js  c++  java
  • 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 来捕获异常,重新再从头过一轮数据进行训练。

  • 相关阅读:
    Node.js运行Vue项目
    DotNetCore知识栈
    Building gRPC Client iOS Swift Note Taking App
    React Native
    Node.js 教程
    SQL 在线教程&在线练习平台
    RxSwift + Moya + ObjectMapper
    浅谈常用的几种web攻击方式
    让MyEclipse支持mac的Retina屏解决字体模糊的问题
    Java设计模式中的单例模式
  • 原文地址:https://www.cnblogs.com/Gelthin2017/p/13223371.html
Copyright © 2011-2022 走看看