使用Python怎么对list、tuple、str和dict进行转换?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
dict = {‘name': ‘Zara', ‘age': 7, ‘class': ‘First'}
返回:
print type(str(dict)), str(dict)
返回:(‘age', ‘name', ‘class')
print tuple(dict)
返回:(7, ‘Zara', ‘First')
print tuple(dict.values())
返回:[‘age', ‘name', ‘class']
print list(dict)
print dict.values
tup=(1, 2, 3, 4, 5)
返回:(1, 2, 3, 4, 5)
print tup.__str__()
返回:[1, 2, 3, 4, 5]
print list(tup)
nums=[1, 3, 5, 7, 8, 13, 20];
返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)
返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)
返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
返回:[1, 2, 3]
print list(eval("(1,2,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'>
关于使用Python怎么对list、tuple、str和dict进行转换问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。