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}"))
補充:python入門之路:一個小錯誤,str變tuple
筆者在編程的時候發(fā)現,原先定義的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))
發(fā)現random_char的type類型已經發(fā)生改變:
<class 'tuple'>
只是一個簡單的賦值,為什么會發(fā)生改變?
原因是在賦值的時候多加了一個逗號。
這個逗號讓編譯器執(zhí)行的時候理解為("str",)
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
Python Django安裝配置模板系統(tǒng)及使用實戰(zhàn)全面詳解
本文首先介紹了Django模板系統(tǒng)的基礎知識,接著探討了如何安裝和配置Django模板系統(tǒng),然后深入解析了Django模板的基本結構、標簽和過濾器的用法,闡述了如何在模板中展示模型數據,最后使用一個實際項目的例子來演示如何在實際開發(fā)中使用Django模板系統(tǒng)2023-09-09將本地Python項目打包成docker鏡像上傳到服務器并在docker中運行
Docker是一個開源項目,為開發(fā)人員和系統(tǒng)管理員提供了一個開放平臺,可以將應用程序構建、打包為一個輕量級容器,并在任何地方運行,這篇文章主要給大家介紹了關于將本地Python項目打包成docker鏡像上傳到服務器并在docker中運行的相關資料,需要的朋友可以參考下2023-12-12python+numpy+matplotalib實現梯度下降法
這篇文章主要為大家詳細介紹了python+numpy+matplotalib實現梯度下降法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08