python字符串/列表/字典互相转换
生活随笔
收集整理的這篇文章主要介紹了
python字符串/列表/字典互相转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符串與列表
字符串轉列表
1.整體轉換
str1 = 'hello world' print(str1.split('這里傳任何字符串中沒有的分割單位都可以,但是不能為空')) # 輸出:['helloworld']2.分割
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' str2 = "hello world" list2 = list(str2) print(list2) #輸出:['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']str3 = "en oo nn" list3 = str3.split() # list2 = str3.split(" ") print(list3) #輸出:['en', 'oo', 'nn']列表轉字符串
1.拼接
list1 = ['hello','world'] res = list1[0] + list1[1] print(res) # 輸出:helloworld2.join
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' list2 = ['hello','world'] # 引號中的內容為,連接各個字符串的字符 print("".join(list2)) print(" ".join(list2)) print(".".join(list2)) # 輸出:helloworld # 輸出:hello world # 輸出:hello.world字符串與字典
字典轉字符串
1.json
import json dict_1 = {'name':'linux','age':18} dict_string = json.dumps(dict_1) print(type(dict_string)) #輸出:<class 'str'>2.強制
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' dict_2 = {'name':'linux','age':18} dict_string = str(dict_2) print(type(dict_string)) #輸出:<class 'str'>列表與字典
列表轉字典
兩個列表
list1 = ['k1','k2','k3'] 、 list2 = [1,2,3] ,轉換成字典{’k1‘:1,'k2':2,'k3':3}list1 = ['k1','k2','k3'] list2 = [1,2,3] print(dict(zip(list1,list2))) #輸出:{'k1': 1, 'k2': 2, 'k3': 3}zip() 函數用于將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中為了減少內存,zip() 返回的是一個對象。如需展示列表,需手動 list() 轉換;如需展示成字典,需要手動dict()轉換,如果元素個數不對應會報錯。
嵌套列表
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' list2 = [['key1','value1'],['key2','value2'],['key3','value3']] print(dict(list2)) #輸出:{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}字典轉列表
dict = {'name': 'Zara', 'age': 7, 'class': 'First'} print(list(dict)) #輸出:['name', 'age', 'class']總結
以上是生活随笔為你收集整理的python字符串/列表/字典互相转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 函数缓存 (Functio
- 下一篇: Python中enumerate用法详解