溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Python怎么對list、tuple、str和dict進(jìn)行轉(zhuǎn)換

發(fā)布時(shí)間:2021-03-10 14:03:40 來源:億速云 閱讀:212 作者:Leah 欄目:開發(fā)技術(shù)

使用Python怎么對list、tuple、str和dict進(jìn)行轉(zhuǎn)換?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

1、字典(dict)

dict = {‘name': ‘Zara', ‘a(chǎn)ge': 7, ‘class': ‘First'}

1.1 字典——字符串

返回:

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

1.2 字典——元組

返回:(‘a(chǎn)ge', ‘name', ‘class')

print tuple(dict)

1.3 字典——元組

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

print tuple(dict.values())

1.4 字典——列表

返回:[‘a(chǎn)ge', ‘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 元組不可以轉(zhuǎn)為字典

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 列表不可以轉(zhuǎn)為字典

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}"))

補(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)知識。

向AI問一下細(xì)節(jié)

免責(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)容。

AI