Chinaunix首页 | 论坛 | 博客
  • 博客访问: 166984
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 425
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-13 17:05
文章分类

全部博文(31)

文章存档

2016年(11)

2015年(20)

我的朋友

分类: Python/Ruby

2015-12-30 10:40:58

1、字符串:
    字符串可以使用eval()函数对str进行转换:
        (1)字符串转为元组:

点击(此处)折叠或打开

  1. In [2]: print tuple(eval("(1,2,3,4,5)")),type(tuple(eval("(1,2,3,4,5)")))
  2. (1, 2, 3, 4, 5) <type 'tuple'>
        (2)字符串转为列表:

点击(此处)折叠或打开

  1. In [3]: print list(eval("(1,2,3,4,5)")),type(list(eval("(1,2,3,4,5)")))
  2. [1, 2, 3, 4, 5] <type 'list'>
        (3)字符串转为字典:

点击(此处)折叠或打开

  1. In [5]: print eval("{'x':1,'y':2}"),type(eval("{'x':1,'y':2}"))
  2. {'y': 2, 'x': 1} <type 'dict'>

2、元组:
        (1)元组转为字符串:

点击(此处)折叠或打开

  1. In [9]: t1 = (1,2,3,4)

  2. In [10]: print t1.__str__(),type(t1.__str__())
  3. (1, 2, 3, 4) <type 'str'>
        (2)元组转为列表:

点击(此处)折叠或打开

  1. In [13]: print list(t1),type(list(t1))
  2. [1, 2, 3, 4] <type 'list'>
        (3)元组无法转为字典

3、列表:
        (1)列表转为字符串:

点击(此处)折叠或打开

  1. In [15]: print str(l1),type(str(l1))
  2. [1, 2, 3, 4] <type 'str'>
        (2)列表转为元组:

点击(此处)折叠或打开

  1. In [17]: print tuple(l1),type(tuple(l1))
  2. (1, 2, 3, 4) <type 'tuple'>
        (3)列表无法转为字典

4、字典:
        (1)字典转为字符串:

点击(此处)折叠或打开

  1. In [19]: print str(d1),type(str(d1))
  2. {'y': 2, 'x': 1, 'z': 3} <type 'str'>
        (2)字典转为元组(转换后的元组为键):

点击(此处)折叠或打开

  1. In [21]: print tuple(d1),type(tuple(d1))
  2. ('y', 'x', 'z') <type 'tuple'>
        (3)字典转为元组(转换后的元组为值):

点击(此处)折叠或打开

  1. In [23]: print tuple(d1.values()),type(tuple(d1.values()))
  2. (2, 1, 3) <type 'tuple'>
        (4)字典转为列表(转换后的列表为键):

点击(此处)折叠或打开

  1. In [27]: print list(d1),type(list(d1))
  2. ['y', 'x', 'z'] <type 'list'>
        (5)字典转为列表(转换后的列表为值):

点击(此处)折叠或打开

  1. In [28]: print list(d1.values()),type(list(d1.values()))
  2. [2, 1, 3] <type 'list'>
阅读(1821) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~