您好,登錄后才能下訂單哦!
使用Python怎么對list、tuple、str和dict進(jìn)行轉(zhuǎn)換?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
dict = {‘name': ‘Zara', ‘a(chǎn)ge': 7, ‘class': ‘First'}
返回:
print type(str(dict)), str(dict)
返回:(‘a(chǎn)ge', ‘name', ‘class')
print tuple(dict)
返回:(7, ‘Zara', ‘First')
print tuple(dict.values())
返回:[‘a(chǎn)ge', ‘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}"))
補(bǔ)充:python入門之路:一個(gè)小錯(cuò)誤,str變tuple
筆者在編程的時(shí)候發(fā)現(xiàn),原先定義的str字符串在傳遞和引用的時(shí)候會莫名其妙改變類型,變成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函數(shù)輸出一個(gè)隨機(jī)字符串,可以看到type類型為:
<class 'str'>
在另一個(gè)文件中進(jìn)行引用:
from random_data.py import get_Veri get_veri=get_Veri() random_char = get_veri.random_char(), print(random_char) print(type(random_char))
發(fā)現(xiàn)random_char的type類型已經(jīng)發(fā)生改變:
<class 'tuple'>
關(guān)于使用Python怎么對list、tuple、str和dict進(jìn)行轉(zhuǎn)換問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。