#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]