zoukankan      html  css  js  c++  java
  • 可以字符串string转化成list,tuple,dict的eval()方法

    
    

    功能:将字符串str当成有效的表达式来求值并返回计算结果。

    
    

      语法: eval(source[, globals[, locals]]) -> value

    
    

      参数:

    
    

        source:一个Python表达式或函数compile()返回的代码对象

    
    

        globals:可选。必须是dictionary

    
    

        locals:可选。任意map对象


    可以把list,tuple,dict和string相互转化。
    ################################################# 字符串转换成列表 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" >>>type(a) <type 'str'> >>> b = eval(a) >>> print b [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] >>> type(b) <type 'list'> ################################################# 字符串转换成字典 >>> a = "{1: 'a', 2: 'b'}" >>> type(a) <type 'str'> >>> b = eval(a) >>> print b {1: 'a', 2: 'b'} >>> type(b) <type 'dict'> ################################################# 字符串转换成元组 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))" >>> type(a) <type 'str'> >>> b = eval(a) >>> print b ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0)) >>> type(b) <type 'tuple'>
  • 相关阅读:
    spring-mvc dispatcherServlet
    常用注解
    spring基础
    消息转换
    高级装配
    Leetcode第242题:有效的字母异位词
    Leetcode第76题:最小覆盖子串
    Leetcode633题平方数之和
    Leetcode454题四数之和II
    java从虚拟机执行角度解析案例(转)
  • 原文地址:https://www.cnblogs.com/chillytao-suiyuan/p/9140037.html
Copyright © 2011-2022 走看看