(備忘)Python字符串、元組、列表、字典互相轉換的方法

#一、字典
dict = { 'name' : 'Zara' , 'age' : 7 , 'class' : 'First' }
#字典轉爲字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', '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)" ))
#字符串轉爲字典,返回:<type 'dict'>
print type ( eval ( "{'name':'ljq', 'age':24}" ))
相關文章
相關標籤/搜索