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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM