Python基礎:字符串str & 列表list & 元組tuple & 字典dict & 集合setpython
字符串是以單引號或雙引號括起來的任意文本git
字符串不可變centos
建立字符串 str1 = "lee is a good man!" str2 = "lee is a nice man!" str3 = "lee is a handsome man!"
字符串拼接api
str6 = "lee is a " str7 = "good man" str8 = str6 + str7 print("str6 =", str6) print("str7 =", str7) print("str8 =", str8) a="hello"+"-"*50+"world" print(a) print(a.__len__()) print(len(a))
輸出重複字符串數據結構
輸出重複字符串 str9 = "good" str10 = str9 * 3 print("str10 =", str10)
訪問字符串中的某一個字符app
經過索引下標查找字符 字符串名[下標] str11 = "lee is a good man!" print(str11[1]) #str11[1] = "a" #打印會報錯,由於字符串不可變 #print("str11 =", str11)
字符串取值(切片)ide
str12 = "to day is a good day" print(str12[5:10]) # 從給定下標開始截取到給定下標以前 print(str12[:4]) # 從頭截取到給定下標以前 print(str12[14:]) # 從給定下標處開始截取到結尾 print(str12[:]) # :號先後都省略,則表示全取列表全部的值;但這樣寫比較怪,不如直接print(str12) print(str12[::2]) # 第一個:號先後都省略,表示全取,第二個:號後的數字2表示步長(和循環裏的步長一致) print(str12[::-1]) #列表反轉,相似os.reverse()
字符串判斷函數
str13 = "lee is a good man!" print("good" in str13) print("good" not in str13)
格式化輸出編碼
print("lee is a good man") num = 10 str14 = "lee is a nice man!" f = 10.14567 print("num =", num) # %d %s %f 佔位符 # %.2f 精確到小數後2位,會四捨五入 print("num = %d, str14 = %s, f = %.2f" %(num,str14,f))
abc="Hello,nice to meet you" print(len(abc)) # 打印字符串的長度 print(abc.__len__()) # 打印字符串的長度 print(abc.lower()) # 轉換字符串中大寫字母爲小寫字母 print(abc.upper()) # 轉換字符串中小寫字母爲大寫字母 print(abc.swapcase()) # 轉換字符串中大寫字母爲小寫字母,小寫字母爲大寫字母 print(abc.capitalize()) # 整個字符串中首字母大寫,其餘所有小寫 print(abc.title()) # 每一個單詞的首字母大寫 print(abc.center(50, "*")) # 一共50個字符,字符串放中間,不夠的兩邊補* print(abc.ljust(50, "*")) # 一共50個字符,字符串放左邊,不夠的左邊補* print(abc.rjust(50, "*")) # 一共50個字符,字符串放右邊,不夠的右邊補* print(abc.zfill(50)) # 一共50個字符,字符串放右邊,不夠的右邊補0 print(abc.count("t")) # 統計字符串裏t出現了多少次 print(abc.find("to")) # 找出to在字符串中的第幾位 print(abc.rfind("to")) # 找出最後一個to在字符串中的第幾位 print(abc.index("to")) # 和find同樣的查找,只不過若是to不存在的時候會報一個異常 print(abc.rindex("to")) # 和rfind同樣的查找,只不過若是to不存在的時候會報一個異常 print(" haha\n".split()) # 刪除字符串左邊和右邊的空格或換行 print(" haha\n".lstrip()) # 刪除字符串左邊的空格或換行 print(" haha\n".rstrip()) # 刪除字符串右邊的空格或換行 print(abc.endswith("you")) # 判斷字符串是否以you結尾 print(abc.startswith("Hello")) # 判斷字符串是否以hello開始 print(abc.isalnum()) # 判斷字符串中是否只有字母或數字 print(abc.isalpha()) # 判斷字符串是否都是字母 print(abc.isdecimal()) # 判斷字符串中是否只包含十進制字符 print(abc.isdigit()) # 判斷字符串中是否只有數字 print(abc.islower()) # 判斷字符串中的字符是否都是小寫的英文字母 print(abc.isnumeric()) # 判斷字符串中是否只有數字 print(abc.isspace()) # 判斷字符串中是否只包含空格
# eval(str) # 功能:將字符串str當成有效的表達式來求值並返回計算結果 print(eval("+123")) print(eval("-123")) print(eval("12+3")) print(eval("12-3")) # len(str) # 返回字符串的長度(字符個數) print(len("lee is a good man!")) # lower() # 轉換字符串中大寫字母爲小寫字母 str15 = "LEE is a Good Man!" print(str15.lower()) # upper() # 轉換字符串中小寫字母爲大寫字母 str16 = "LEE is a Good Man!" print(str16.upper()) print("LEE is a Good Man!".upper()) # swapcase() # 轉換字符串中大寫字母爲小寫字母,小寫字母爲大寫字母 str17 = "LEE is a Good Man!" print(str17.swapcase()) # capitalize() # 首字母大寫,其餘小寫 str18 = "LEE is a Good Man!" print(str18.capitalize()) # title() # 每一個單詞的首字母大寫 str19 = "LEE is a Good Man!" print(str19.title()) # center(width[,fillchar]) # 返回一個指定寬度的居中字符串,fillchar爲填充的字符串,默認是空格填充 str20 = "lee is a nice man!" print(str20.center(40,"*")) # ljust(width[,fillchar]) # 返回一個指定寬度的左對齊字符串,fillchar爲填充的字符串,默認是空格填充 str21 = "lee is a nice man!" print(str21.ljust(40,"%")) # rjust(width[,fillchar]) # 返回一個指定寬度的右對齊字符串,fillchar爲填充的字符串,默認是空格填充 str22 = "lee is a nice man!" print(str22.rjust(40,"%")) # zfill(width) # 返回一個長度爲width的字符串,原字符串右對齊,前面補0 str23 = "lee is a nice man!" print(str23.zfill(40)) # count(str[,start][,end]) # 返回字符串中strc出現的次數,能夠指定一個範圍,默認從頭至尾 str24 = "lee is a very very nice man!" print(str24.count("very")) print(str24.count("very",9,len(str24))) # find(str[,start][,end]) # 從左向右檢測str字符串是否包含在字符串中,能夠指定範圍,默認從頭至尾,獲得的是第一次出現的開始下標,沒有返回-1 str25 = "lee is a very very nice man!" print(str25.find("very")) print(str25.find("good")) print(str25.find("very",8,len(str25))) # rfind(str[,start][,end]) str25 = "lee is a very very nice man!" print(str25.rfind("very")) print(str25.rfind("good")) print(str25.rfind("very",8,len(str25))) # index(str,start=0,end=len(str)) # 跟find()同樣,只不過若是str不存在的時候會報一個異常 str26 = "lee is a very very nice man!" print(str26.index("very")) # rndex(str,start=0,end=len(str)) # 跟rfind()同樣,只不過若是str不存在的時候會報一個異常 str27 = "lee is a very very nice man!" print(str27.rindex("very")) # lstrip() # 截掉字符串左側指定的字符,默認爲空格 str28 = "*******lee is a nice man!" print(str28.lstrip("*")) # rstrip() # 截掉字符串右側指定的字符,默認爲空格 str29 = "lee is a nice man! " print(str29.rstrip(),"*") # strip() # 截掉字符串兩側指定的字符,默認爲空格 str30 = "******lee is a nice man******" print(str30.strip("*")) # split(str="",num) # 以str爲分隔符截取字符串,指定num,則僅截取num個字符串 str31 = "lee***is*****a**good**man" print(str31.split("*")) list39 = str31.split("*") c = 0 for s in list39: if len(s) > 0: c += 1 print(c) # splitlines([keepends]) # 按照('\r', '\r\n', '\n')分割 # keepends == True 會保留換行符 str32 = ''' lee is a good man! lee is a nice man! lee is a handsome man! ''' print(str32.splitlines()) # join(seq) #以指定的字符串分隔符,將seq中的全部元素組合成一個字符串 list33 = ['lee','is','a','good','man'] str33 = " ".join(list33) print(str33) # max() min() str34 = "lee is a good man z" print(max(str34)) print("*"+min(str34)+"*") # replace(oldstr,newstr,count) # 用newstr替換oldstr,默認是所有替換。若是指定了count,那麼只替換前count個 str35 = "lee is a good good good man" str36 = str35.replace("good","nice",1) print(str36) # 建立一個字符串映射表 # 要轉換的字符串, 目標字符串 str37 = str.maketrans("ac","65") # a--6 c--5 str38 = "lee is a good man" str39 = str38.translate(str37) print(str39) # startswith(str,start=0,end=len(str)) # 在給定的範圍內是不是以給定的字符串開頭的,若是沒有指定範圍,默認整個字符串 str40 = "lee is a good man" print(str40.startswith("lee",5,14)) # endswith(str,start=0,end=len(str)) # 在給定的範圍內是不是以給定的字符串結尾的,若是沒有指定範圍,默認整個字符串 str41 = "lee is a good man" print(str41.endswith("man")) # 編碼 #encode(encoding="utf-8",errors="strict") str42 = "lee is a good man傑" #ignore 忽略錯誤 date42 = str42.encode("utf-8","ignore") print(date42) # 解碼 注意:要與編碼時的編碼格式一致 str43 = date42.decode("gbk","ignore") print(str43) # isalpha() # 若是字符串中至少有一個字符且全部的字符都是字母返回True,不然返回False str44 = "leeisagoodman" print(str44.isalpha()) # isalnum() # 若是字符串中至少有一個字符且全部的字符都是字母或數字返回True,不然返回False str45 = "12a3" print(str45.isalnum()) # isupper() # 若是字符串中至少有一個英文字符且全部的字符都是大寫的英文字母返回True,不然返回False print("ABD".isupper()) print("AbC".isupper()) print("ABC".isupper()) print("ABD#".isupper()) # islower() # 若是字符串中至少有一個英文字符且全部的字符都是小寫的英文字母返回True,不然返回False print("abc".islower()) print("Abcd".islower()) print("ABCD".islower()) print("abc1".islower()) print("abc!".islower()) # istitle() # 若是字符串是標題化的返回True,不然返回False print("Lee Is".istitle()) print("Lee is".istitle()) print("lee is".istitle()) # isdigit() # 若是字符串只包含數字字符返回True,不然返回False print("123".isdigit()) print("123a".isdigit() # isnumeric() # 同上 print("123".isnumeric()) print("123s".isnumeric()) # isdecimal() # 字符串中只包含十進制字符 print("123".isdecimal()) print("123a".isdecimal()) # 若是字符串中只包含空格返回True,不然返回False print(" ".isspace()) print(" ".isspace()) print("\t".isspace()) print("\n".isspace()) print("\r".isspace())
列表是一種基本的序列數據結構,是一種可變值的數據類型;使用中括號表示[]spa
列表中的每一個元素配有下標(或者叫索引); 第一個爲0,第二個爲1,以此類推,每一個元素用逗號隔開,裏面能夠存放各類數據類型好比:
li = [‘alex’,123,Ture,(1,2,3,’wusir’),[1,2,3,’小明’,],{‘name’:’alex’}]
格式:列表名 = [ 列表選項1, 列表選項2, ,,,,,, 列表選項n]
#建立一個空列表 list1 = [] print(list1) #建立帶有元素的列表 list2 = [18, 19, 20, 21, 22] index = 0 sum = 0 #嵌套最好不要超過3層 while index < 5: sum += list2[index] index += 1 if index == 5: print("平均年齡:%d" %(sum / 5)) #注意:列表中的元素數據能夠是不一樣類型的 list3 = [1, 2, 3, "lee", "good", True] print(list3)
# 在列表的末尾添加新的元素 list12 = [1,2,3,4,5] list12.append(6) list12.append([7,8,9]) print(list12) # 在末尾一次性追加另外一個列表中的多個值 list13 = [1,2,3,4,5] list13.extend([6,7,8]) # 迭代的去增 print(list13) # 根據索引增長,不覆蓋原數據,原數據向後順延 list14 = [1,2,3,4,5] list14.insert(3,100) list14.insert(3,[44,22]) print(list14)
# pop(x=list[-1]) # 移除列表中指定下標處的元素(默認移除最後一個元素),並返回刪除的數據 list15 = [1,2,3,4,5] list15.pop() list15.pop(2) print(list15.pop(1)) print(list15) # remove 移除列表中的某個元素第一個匹配的結果 list16 = [1,2,3,4,5,6,3,4,2] list16.remove(4) print(list16) # 按照位置去刪除,也可切片刪除沒有返回值 # del li[1:3] # print(li) # 清除列表中全部的數據 list17 = [1,2,3,4,5] list17.clear() print(list17)
li = [1, 'a', 'b', 2, 3, 'a'] li[1] = "test" print(li) >打印結果 [1, 'test', 'b', 2, 3, 'a'] li[1:3] = ['A', 'B'] print(li) >打印結果 [1, 'A', 'B', 2, 3, 'a']
能夠經過切片查, 或者經過循環去查
#列表元素的訪問 #注意不要越界(下標超出了可表示的範圍) #取值 格式:列表名[下標] list4 = [1, 2, 3, 4, 5] print(list4[2])
os=["rhel","centos","suse"] print(len(os)) #打印列表裏元素的個數 print(max(os)) #打印最大元素 print(min(os)) #打印最小元素 print(os[0]) #取列表中的第一個 print(os[1]) #取列表中的第二個 print(os[2]) #取列表中的第三個 print(os[1:3]) #取列表中的第二個到第三個(注意:不包含第四個) print(os[0:-1]) #取列表中的第一個到倒數第二個(注意:不包含最後一個) print(os[2:]) #取列表中的第三個到最後一個 print(os[:2]) #取列表中的第一個到第二個(注意:不包含第三個) print(os[:]) # :號先後都省略,則表示全取列表全部的值;但這樣寫比較怪,不如直接print(os) print(os[::2]) # 第一個:號先後都省略,表示全取,第二個:號後的數字2表示步長(和循環裏的步長一致) print(os[::-1]) #列表反轉,相似os.reverse()
# 從列表中找出某個值第一個匹配的索引值 list18 = [1,2,3,4,5,3] index18 = list18.index(3) index19 = list18.index(3,3,6) print(index18) print(index19) # 列表中元素的個數 list20 = [1,2,3,4,5] print(len(list20)) # 獲取列表中的最大值 list21 = [1,2,3,4,5] print(max(list21) # 獲取列表中的最小值 list22 = [1,2,3,4,5] print(min(list22)) # 倒序 list25 = [1,2,3,4,5] list25.reverse() print(list25) # 升序排序 list26 = [2,3,4,1,5] list26.sort() print(list26)
#找出第二大的值 # 方法一 listNum = [] num = 0 while num < 10: val = int(input()) listNum.append(val) num += 1 print(listNum) listNum.sort() #按照升序排序 count = listNum.count(listNum[len(listNum) -1]) c = 0 while c < count: listNum.pop() c += 1 print(listNum[len(listNum) -1]) # 方法二 listNum = [] num = 0 while num < 10: val = int(input()) listNum.append(val) num += 1 if listNum[0] >= listNum[1]: max = listNum[0] sec = listNum[1] else: max = listNum[1] sec = listNum[0] index = 2 while index < len(listNum): if listNum[index] >= sec: sec = listNum[index] if listNum[index] >= max: sec = max max = listNum[index] index += 1 print(sec)
元組也是一種有序集合,與列表類似,一旦初始化就不能修改,使用小括號表示 ()
#建立tuple #格式:元組名 = (元組元素1, 元組元素2, ……, 元組元素n) #建立空的元組 tuple1 = () print(tuple1) #建立帶有元素的元組 #元組中的元素的類型能夠不一樣 tuple2 = (1,2,3,"good",True) print(tuple2) #定義只有一個元素的元組 tuple3 = (1,) print(tuple3) print(type(tuple3))
# 元組元素的訪問 # 格式:元組名[] # 下標從0開始 tuple4 = (1,2,3,4,5) print(tuple4[1]) print(tuple4[-1]) # 獲取最後一個元素 print(tuple4[-2]) # 元組的截取 # 格式:元組名[開始下標:結束下標] # 從開始下標開始截取,截取到結束下標以前 tuple12 = (1,2,3,4,5,6,7,8) print(tuple12[3:7]) print(tuple12[3:]) print(tuple12[:7]) # 二維元組:元素爲一維元組的元組 tuple13 = ((1,2,3),(4,5,6),(7,8,9)) print(tuple13[1][1]) # 判斷元素是否在元組中 tuple11 = (1,2,3) print(4 in tuple11)
#len() 返回元組中元素的個數 tuple14 = (1,2,3,4,5) print(len(tuple14)) #max() 返回元組中的最大值 print(max((5,6,7,8,9))) #min() 返回元組中的最小值 print(min(1,2,3,4,5)) #將列表轉成元組 list1 = [1,2,3] tuple15 = tuple(list1) print(tuple15) #元組的遍歷 for i in (1,2,3,4,5): print(i)
tuple6 = (1,2,3) del tuple6 #print(tuple6)
字典是python中惟一的映射類型,採用鍵值對(key-value)的形式存儲數據。python對key進行哈希函數運算,根據計算的結果決定value的存儲地址,因此字典是無序存儲的,且key必須是可哈希的。可哈希表示key必須是不可變類型,如:數字、字符串、元組。
字典(dictionary)是除列表意外python之中最靈活的內置數據結構類型。列表是有序的對象結合,字典是無序的對象集合。二者之間的區別在於:字典當中的元素是經過鍵來存取的,而不是經過偏移存取。
{Key1:value2, Key2:value2}
鍵與值用冒號「:」分開;
項與項用逗號「,」分開;
key的特性
一、字典中的key必須惟一
二、key是不可變的對象
三、字符串、數字等都是不可變的,能夠做爲key
四、list是可變的,不能做爲key
思考:保存多位學生的姓名與成績
[["tom",60],["lilei",70]]
使用字典,學生姓名爲key,學生成績做爲值
dict1 = {"tom":60, "lilei":70}
dict1["stu05"]="tianqi" #相似修改,若是key值不存在,則就增長 print(dict1)
dict1.pop("stu05") # 刪除這條記錄值,返回刪除的value del dict1["stu05"] # 刪除這條記錄值, dict1.popitem() # 刪除顯示的最後一條 dict1.clear() # 清空字典
dic = {"name":"jin","age":18,"sex":"male"} dic2 = {"name":"alex","weight":75} dic2.update(dic) # 將dic全部的鍵值對覆蓋添加(相同的覆蓋,沒有的添加)到dic2中 print(dic2) dict1["stu04"]="馬六" #相似增長,若是key值存在,則就修改 print(dict1)
print(dict1["stu01"]) #不建議這種方法,若是key值不存在,會返回keyerror錯誤 print(dict1.get("stu01")) #這種取值方法若是key值不存在,會返回none,不會返回錯誤
print("stu01" in dict1) #判斷鍵stud01是否在字典裏,在則返回True,不在則返回False print(dict1.items()) #字典轉成列表套元組 print(list(dict1)) #這種只能看到key print(dict1.keys()) #打印全部的keys print(dict1.values()) #打印全部的values dict1.setdefault("stu08","老八") #有這個key,則不改變;沒有這個key,則增長這個key和value # if "stu08" in dict1: # pass # else: # dict1["stu08"]="老八" #這個判斷也能夠實現setdefault的方法效果
dict1 = { 'stu01':"zhangsan", 'stu02':"lisi", 'stu03':"wangwu", 'stu04':"maliu", } #建議用這種來作字典循環,效率高 for i in dict1: print(i,dict1[i]) #這種循環效率比上面的差 for i,j in dict1.items(): print(i,j) #只循環key for i in dict1.keys(): print(i) #只循環value for i in dict1.values(): print(i)
字典和列表的比較
#dict #一、查找和插入的速度極快不會隨着key-vaule的增長而變慢 #二、須要佔用大量的內存,內存浪費多 #list #一、查找和插入的速度會隨着數據量的增多而減慢 #一、佔用空間小,浪費內存少
# 輸入一個單詞,判斷出現了多少次 w = input() d = {} # word:次數 str = "lee is a good man! lee is a nice man! lee is a greate man! lee is a hands man! lee is a good man! lee is a noble man!" l = str.split(" ") for v in l: c = d.get(v) if c == None: d[v] = 1 else: d[v] += 1 print(d[w]) ''' 一、以空格切割字符串 二、循環處理列表中的每一個元素 三、以元素當作key去一個字典中提取數據 四、若是沒有提取到,就以該元素做爲key,1做爲value存進字典 五、若是提取到,將對應的key的value修改,值加1 六、根據輸入的字符串當作key再去字典取值 '''
set相似dict,是一組key的集合,不存儲value
本質:無序和無重複元素的集合
#建立 #建立set須要一個list或者tuple或者dict做爲輸入 #重複元素在set中會自動被過濾 set1 = set([1,2,3,4,5,5,4,3,3]) print(set1) set2 = set((1,2,3,4,3,2)) print(set2) set3 = set({1:"good",2:"nice"}) print(set3)
# add , update
set4 = set([1,2,3,4,5]) set4.add(6) set4.add(4) #能夠添加劇復的,可是不會有效果 #set4.add([7,8,9]) #set的元素不能是列表,由於列表是可變的 set4.add((7,8,9)) #set4.add({4:"good"}) #set的元素不能是字典,由於字典也是可變的 print(set4) #插入整個list、tuple、字符串,打碎插入 set5 = set([1,2,3,4,5]) set5.update([6,7,8]) set5.update((9,10)) set5.update("sunck") print(set5)
set6 = set([1,2,3,4,5]) set6.remove(3) # remove刪除一個不存在的元素會報錯 print(set6) set6.discard(666) # discard刪除一個不存在的元素不會報錯,存在則刪除 print(set1)
set1=[1,4,7,5,9,6] set2=set([2,4,5,9,8]) # 交集 print(set1.intersection(set2)) print(set1 & set2) print(set1.isdisjoint(set2)) # 判斷兩個集合是否有交集,有則返回true;沒有則返回false # 並集 print(set1.union(set2)) print(set1 | set2) # 差集(補集) print(set1.difference(set2)) #set1裏有,set2裏沒有 print(set1-set2) print(set2.difference(set1)) #set2裏有,set1裏沒有 print(set2-set1) # 對稱差集 print(set1.symmetric_difference(set2))#我有你沒有的 加上 你有我沒有的 print(set1^set2) # 子集 set3=set([4,5]) print(set3.issubset(set1)) #判斷set3是否爲set1的子集 print(set1.issuperset(set3)) #判斷set1是否包含set3
# 遍歷 set7 = set([1,2,3,4,5]) for i in set7: print(i) # set沒有索引 # print(set7[2]) for index,i in enumerate(set7): print(index,i)
數字
字符串
集合:無序,即無序存索引相關信息
元組:有序,須要存索引相關信息,不可變
列表:有序,須要存索引相關信息,可變,須要處理數據的增刪改
字典:無序,須要存key與value映射的相關信息,可變,須要處理數據的增刪改
標量/原子類型 | 數字,字符串 |
容器類型 | 列表,元組,字典 |
可變 | 列表,字典 |
不可變 | 數字,字符串,元組,布爾值 |
直接訪問 | 數字 |
順序訪問(序列類型) | 字符串,列表,元組 |
key值訪問(映射類型) | 字典 |
#list > set l1 = [1,2,3,4,5,5,3,2,5,6,9] print(set(l1)) #tuple > set t1 = (1,2,3,4,4,5,2) print(set(t1)) #set > list s1 = {1,2,3,4} print(list(s1)) #set > tuple s2 = {1,2,3,4,5} print(tuple(s2))