Python中字符串、列表、元組、集合以及字典轉換

#list 方括號[],列表,   有序   可索引   可修改    有重複
#tuple 括號() 元組      有序   可索引   無修改     有重複
#set 書括號{} 集合      無序   無索引   可修改     無重複
#dict  [key:val]字典   無序   有索引    可修改    無重複
myStr = "Hello World"
#字符串轉換成其他數據類型:

myList=list(mystr)    # ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
myTuple=tuple(mystr)  #('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
mySet = set(myStr)   #{'l', 'H', 'o', 'r', 'W', 'd', 'e', ' '}  一種無序的集合
myDict=dict.fromkeys(mystr)  
#{'H': None, 'e': None, 'l': None, 'o': None, ' ': None, 'W': None, 'r': None, 'd': None}


myList= ["a", "b", "a", "c", "c"]
列表轉換成其他類型:

myStr="".join(myList)  #'abacc'
myTuple=tuple(myList)  #("a", "b", "a", "c", "c")
mySet=set(myList)   #{'b', 'a', 'c'}  無序
myDict=dict.fromkeys(myList)  #{'b': None, 'a': None, 'c': None}

練習題:

1、從列表中刪除任何重複項

 myList= ["a", "b", "a", "c", "c"]

myTmp=set(myStr) #先轉換成集合去除重複,再轉換成list
print('第一種方法:',list(myTmp))         #["b", "a", "c"]
myRes = list(dict.fromkeys(myList)) #先轉換成元組去除重複,再轉換成list
print('第二種方法:',myRes)

 

2、如何反轉 Python 中的字符串:反轉字符串 "Hello World" 輸出:dlrow olleH

myStr = "Hello World"

第1種方法:
myRes=""
for x in range(len(myStr)):
    myRes+=myStr[len(myStr)-1-x]
print('第1種方法:',myRes)      #dlrow olleH

第2種方法:先將字符串轉換成列表,使用列表的reverse反轉函數,最後再轉換爲字符串
myStr2=list(myStr)
myStr2.reverse()
print('第2種方法:',"".join(myStr2))

第3種方法:字符串切片
print(myStr[-1::-1])或者print(myStr[::-1])    #dlrow olleH
#切片的語法爲 b = a[start_index: end_index: step]

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章