Python 实现list,tuple,str和dict之间的相互转换

1、字典(dict)

dict = {‘name': ‘Zara', ‘age': 7, ‘class': ‘First'}

1.1 字典——字符串

返回:

print type(str(dict)), str(dict)

1.2 字典——元组

返回:(‘age', ‘name', ‘class')

print tuple(dict)

1.3 字典——元组

返回:(7, ‘Zara', ‘First')

print tuple(dict.values())

1.4 字典——列表

返回:[‘age', ‘name', ‘class']

print list(dict)

1.5 字典——列表

print dict.values

2、元组

tup=(1, 2, 3, 4, 5)

2.1 元组——字符串

返回:(1, 2, 3, 4, 5)

print tup.__str__()

2.2 元组——列表

返回:[1, 2, 3, 4, 5]

print list(tup)

2.3 元组不可以转为字典

3、列表

nums=[1, 3, 5, 7, 8, 13, 20];

3.1 列表——字符串

返回:[1, 3, 5, 7, 8, 13, 20]

print str(nums)

3.2 列表——元组

返回:(1, 3, 5, 7, 8, 13, 20)

print tuple(nums)

3.3 列表不可以转为字典

4、字符串

4.1 字符串——元组

返回:(1, 2, 3)

print tuple(eval("(1,2,3)"))

4.2 字符串——列表

返回:[1, 2, 3]

print list(eval("(1,2,3)"))

4.3 字符串——字典

返回:

print type(eval("{'name':'ljq', 'age':24}"))

补充:python入门之路:一个小错误,str变tuple

笔者在编程的时候发现,原先定义的str字符串在传递和引用的时候会莫名其妙改变类型,变成tuple。

import random
class get_Veri(object):
  def random_color(self):
    random_color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    return random_color

  def random_num(self):
    random_num = str(random.randint(0, 9))
    return random_num

  def random_lowerchr(self):
    random_lowerchar=chr(random.randint(97, 122))
    return random_lowerchar

  def random_upperchr(self):
    random_upperchr = chr(random.randint(65, 90))
    return random_upperchr

  def random_char(self):
    random_char = random.choice([get_Veri.random_num(self), get_Veri.random_upperchr(self), get_Veri.random_lowerchr(self)])
    print(random_char)
    print(type(random_char))
    return random_char

这里random_char函数输出一个随机字符串,可以看到type类型为:

<class 'str'>

在另一个文件中进行引用:

from random_data.py import get_Veri 

get_veri=get_Veri()
random_char = get_veri.random_char(),
print(random_char)
print(type(random_char))

发现random_char的type类型已经发生改变:

<class 'tuple'>

只是一个简单的赋值,为什么会发生改变?

原因是在赋值的时候多加了一个逗号。

这个逗号让编译器执行的时候理解为("str",)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • Python字符串、元组、列表、字典互相转换的方法

    废话不多说了,直接给大家贴代码了,代码写的不好还去各位大侠见谅. #-*-coding:utf-8-*- #1.字典 dict = {'name': 'Zara', 'age': 7, 'class': 'First'} #字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'} print type(str(dict)), str(dict) #字典可以转为元组,返回:('age', 'name', 'class

  • 在Python中字符串、列表、元组、字典之间的相互转换

    一.字符串(str) 字符串转换为列表 使用list()方法 str_1 = "1235" str_2 = 'zhangsan' str_3 = '''lisi''' tuple_1 = list(str_1) tuple_2 = list(str_2) tuple_3 = list(str_3) print(type(tuple_1)) print(type(tuple_2)) print(type(tuple_3)) print(tuple_1) print(tuple_2) pr

  • Python list和str互转的实现示例

    一.list转字符串 命令:''.join(list) 其中,引号中是字符之间的分割符,如",",";","\t"等等 如: list = [1, 2, 3, 4, 5] ''.join(list) 结果即为:12345 ','.join(list) 结果即为:1,2,3,4,5 二.字符串转list print list('12345') 输出: ['1', '2', '3', '4', '5'] print list(map(int, '12

  • Python 实现list,tuple,str和dict之间的相互转换

    1.字典(dict) dict = {'name': 'Zara', 'age': 7, 'class': 'First'} 1.1 字典--字符串 返回: print type(str(dict)), str(dict) 1.2 字典--元组 返回:('age', 'name', 'class') print tuple(dict) 1.3 字典--元组 返回:(7, 'Zara', 'First') print tuple(dict.values()) 1.4 字典--列表 返回:['age

  • python Yaml、Json、Dict之间的转化

    Json To Dict import json jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; print(jsonData) print(type(jsonData)) text = json.loads(jsonData) print(text) print(type(text)) ####################### {"a"

  • Python内建类型str源码学习

    目录 引言 1 Unicode 2 Python中的Unicode 2.1 Unicode对象的好处 2.2 Python对Unicode的优化 3 Unicode对象的底层结构体 3.1 PyASCIIObject 3.2 PyCompactUnicodeObject 3.3 PyUnicodeObject 3.4 示例 4 interned机制 5 总结 引言 “深入认识Python内建类型”这部分的内容会从源码角度为大家介绍Python中各种常用的内建类型. 在介绍常用类型str之前,在上

  • python 将字符串转换成字典dict的各种方式总结

    1)利用eval可以将字典格式的字符串与字典户转 >>>mstr = '{"name":"yct","age":10}' 转换为可以用的字典: >>>eval(mstr), type( eval(mstr) ) {"name":"yct","age":10}, dict 2).JSON到字典转化: >>>dictinfo = json

  • python中ASCII码字符与int之间的转换方法

    ASCII码转换为int:ord('A') 65 int转为ASCII码:chr(65) 'A' 题目内容: 实现一个凯撒密码的变种算法,对输入字符串进行加解密处理 把字母a-z分别循环对应为相距13个位置的字母n-m,即 原文字母:a b c d e f g h i j k l m n o p q r s t u v w x y z 对应字母:n o p q r s t u v w x y z a b c d e f g h i j k l m 大写字母对应方式与小写字母类似,其他符号(含标点

  • Python自定义一个类实现字典dict功能的方法

    如下所示: import collections class Mydict(collections.UserDict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def __contains__(self, key): return str(key) in self.data def __setitem__(self, key, item): se

  • python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

    python3 json数据格式的转换(dumps/loads的使用.dict to str/str to dict.json字符串/字典的相互转换) Python3 JSON 数据解析 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数: json.dumps(): 对数据进行编码. json.loads(): 对数据进

  • python使用点操作符访问字典(dict)数据的方法

    本文实例讲述了python使用点操作符访问字典(dict)数据的方法.分享给大家供大家参考.具体分析如下: 平时访问字典使用类似于:dict['name']的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法. class DottableDict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self de

  • python将unicode转为str的方法

    问题:  将u'\u810f\u4e71'转换为'\u810f\u4e71' 方法: s_unicode = u'\u810f\u4e71' s_str = s_unicode.encode('unicode-escape').decode('string_escape') 以上这篇python将unicode转为str的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • python中in在list和dict中查找效率的对比分析

    首先给一个简单的例子,测测list和dict查找的时间: import time query_lst = [-60000,-6000,-600,-60,-6,0,6,60,600,6000,60000] lst = [] dic = {} for i in range(100000000): lst.append(i) dic[i] = 1 start = time.time() for v in query_lst: if v in lst: continue end1 = time.time

随机推荐