1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 6 #列表的功能之建立 7 #方法1-變量賦值; 8 L1 = [] #定義一個空列表 9 L2 = ['','b','c','d']#存儲4個值,索引爲0~3 10 L3 = ['abc',['def','ghi']]#嵌套列表 11 #方法2,使用python內置方法進行建立; 12 L2 = list() 13 print(L2)
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 L2 = ['a','b','c','d','a','e',1,2]#定義一個列表L2; 6 print(L2[2])#經過索引取值; 7 print(L2[-1])#經過索引從列表右邊開始取值; 8 print(L2.index('a'))#返回指定元素的」索引值「,從左向右查找,找到第一個匹配字符; 9 print(L2.count('a'))#統計指定元素的個數;
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 #把列表當作一個麪包,進行切分查找; 6 L3 = ['Shanshan','Longting','Alex',1,3,4,4,5,6,7,8,8,9,9,0,0,2,3,4,4] 7 print(L3[0-2])#注意,0-2爲-2,等價於print[L3[-2]] 8 print(L3[0-3])#注意,0-3爲-3,等價於print[L3[-3]] 9 print(L3[0:3])#結果爲:['Shanshan', 'Longting', 'Alex'],顧頭不顧尾; 10 print(L3[3:7])#結果爲:[1, 3, 4, 4], 11 print(L3[-1:-5])#結果爲空列表,切片的原則是,只能從左到右進行切分; 12 print(L3[-5:-1])#結果爲:[0, 2, 3, 4],仍舊顧頭不顧尾; 13 print(L3[-5:0])#結果爲:[]空列表 14 print(L3[-5:])#結果爲:[0, 2, 3, 4, 4] 15 print(L3[0:3])#結果爲:['Shanshan', 'Longting', 'Alex'] 16 print(L3[:3])#結果爲:['Shanshan', 'Longting', 'Alex'] 17 print(L3[:])#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4,4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4] 18 print(L3[:7])#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4] 19 print(L3[0:7:2])#結果爲:['Shanshan', 'Alex', 3, 4],引入步長的概念 20 print(L3[:7:1])#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4] 21 print(L3[:-1:3])#結果爲:['Shanshan', 1, 4, 7, 9, 0, 4] 22 print(L3[:-1:4])#結果爲:['Shanshan', 3, 6, 9, 2] 23 print(L3[:])#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4] 24 print(L3[::2])#結果爲:['Shanshan', 'Alex', 3, 4, 6, 8, 9, 0, 2, 4]
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 #列表的插入與追加 6 L4 = ['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4] 7 L4.append('Peiqi')#append方法是「追加」的意思,只能插入到結尾; 8 print(L4)#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi'] 9 L4.insert(0,'abc')#insert方法是根據索引值,進行插入數據; 10 print(L4) 11 L4.insert(2,'Alex') 12 print(L4) 13 #列表的修改-根據索引值修改; 14 print(L4[3]) 15 L4[3] = "龍婷"#列表值的修改,使用從新賦值的方法; 16 print(L4)#結果爲:['abc', 'Shanshan', 'Alex', '龍婷', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi'] 17 #列表的修改-根據索引值的範圍修改; 18 print(L4[4:6])#經過索引範圍,進行批量修改; 19 L4[4:6] = "JACK LIU"# "JACK LIU"分別表示'J', 'A', 'C', 'K', ' ', 'L', 'I', 'U'注意中間有空格,總結8個元素; 20 print(L4)#結果爲:['abc', 'Shanshan', 'Alex', '龍婷', 'J', 'A', 'C', 'K', ' ', 'L', 'I', 'U', 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi']
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 #列表的插入與追加 6 L4 = ['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4] 7 L4.append('Peiqi')#append方法是「追加」的意思,只能插入到結尾; 8 print(L4)#結果爲:['Shanshan', 'Longting', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi'] 9 L4.insert(0,'abc')#insert方法是根據索引值,進行插入數據; 10 print(L4) 11 L4.insert(2,'Alex') 12 print(L4) 13 #列表的修改-根據索引值進行從新賦值修改; 14 print(L4[3]) 15 L4[3] = "龍婷"#列表值的修改,使用從新賦值的方法; 16 print(L4)#結果爲:['abc', 'Shanshan', 'Alex', '龍婷', 'Alex', 1, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi'] 17 #列表的修改-根據索引值的範圍修改 18 print(L4[4:6])#經過索引範圍,進行批量修改; 19 L4[4:6] = "JACK LIU"# "JACK LIU"分別表示'J', 'A', 'C', 'K', ' ', 'L', 'I', 'U'注意中間有空格,總結8個元素; 20 print(L4)#結果爲:['abc', 'Shanshan', 'Alex', '龍婷', 'J', 'A', 'C', 'K', ' ', 'L', 'I', 'U', 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4, 'Peiqi']
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 #列表的循環和排序 6 L6 = ['Shanshan', 'Peiqi', ' ', 'L', 'I', 'U', 3,4, 5, 6, 7,7, 8, 8, 9, 9, 0, 0, 2, 3, 4, 4] 7 for i in L6:#i是臨時變量;for循環; 8 print('loop',i) 9 #range(10),與Python2.x不一樣, 10 for i in range(10): 11 print(i) 12 #for循環與while循環的區別;while循環能夠是死循環,但for循環有邊界,不會出現死循環,區別在於有無循環邊界;
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/7 5 L7 = ['a','e','b',1,34,2,'c'] 6 #L7.sort()#使用sort方法來排序; 7 #print(L7)#TypeError: '<' not supported between instances of 'int' and 'str',int和str沒有關係,因此沒法排序; 8 L7.remove(1)#使用remove方法,刪除指定元素值; 9 L7.remove(34) 10 L7.remove(2) 11 print(L7) 12 L7.append('z')#列表的追加; 13 L7.insert(1,'y')#根據索引值進行增長; 14 L7.insert(3,'A') 15 print(L7) 16 L7.sort()#列表的排序sort方法; 17 print(L7) 18 L7.insert(3,'#') 19 L7.insert(3,'*') 20 L7.insert(3,'!') 21 print(L7)#其實,排序規則是按照列表中元素的位於ASCII碼錶中的位置進行排列顯示的; 22 L7.reverse()#列表的反轉reverse方法與sort互逆; 23 print(L7) 24 L8 = [1,2,4]#新建一個列表; 25 L7.extend(L8)#列表的拓展方法; 26 print(L7) 27 L9 = L7.copy()#列表的copy方法; 28 print(L9) 29 L7.clear()#列表的清空,注意與刪除操做不相同,前者是對內容級別進行操做;後者是列表級別操做; 30 print(L7)#
一、練習題;html
一、 練習題;python
#!/usr/bin/env python # -*- coding:utf-8 -*- # Project: DevelopBasic # Software: PyCharm # DateTime: 2018-10-10 22:19 # File: 12-列表練習題講解.py # __author__: 天晴天朗 # Email: tqtl@tqtl.org # 一、建立一個空列表,命名爲names,往裏面天添加old_driver,rain,jack,shanshan,peiqi,black,black_girl元素; names = [] names.append("old_driver") names.append("rain") names.append("jack") names.append("shanshan") names.append("peiqi") names.append("black") names.append("black_girl") print("No.01:", names) # No.01 ['old_driver', 'rain', 'jack', 'shanshan', 'peiqi', 'black', 'black_girl'] # 二、往names列表裏black_girl前面插入一個alex; names.insert(names.index("black_girl"), "alex") print("No.02:", names) # No.02: ['old_driver', 'rain', 'jack', 'shanshan', 'peiqi', 'black', 'alex', 'black_girl'] # 三、把shanshan的名字改爲中文"姍姍"; names[names.index("shanshan")] = "姍姍" print("No.03:", names) # No.03: ['old_driver', 'rain', 'jack', '姍姍', 'peiqi', 'black', 'alex', 'black_girl'] # 四、往names列表裏rain的後面插入一個子列表["oldboy", "oldgirl"] names.insert(names.index("rain") + 1, ["oldboy", "oldgirl"]) print("No.04:", names) # No.04: ['old_driver', 'rain', ['oldboy', 'oldgirl'], 'jack', '姍姍', 'peiqi', 'black', 'alex', 'black_girl'] # 五、返回peiqi的索引; print("No.05:", names.index("peiqi")) # No.05: 5 # 六、建立新列表[1,2,3,4,2,5,6,2],合併入names列表; nums = list(range(1, 5)) nums.append(2) nums.append(5) nums.append(6) nums.append(2) combine = names + nums print("No.06:", combine) # # No.06: ['old_driver', 'rain', ['oldboy', 'oldgirl'], 'jack', '姍姍', 'peiqi', 'black', 'alex', 'black_girl', 1, 2, 3, 4, 2, 5, 6, 2] # 七、取出names列表中索引4-7的元素 print("No.07:", names[4:8]) # No.07: ['姍姍', 'peiqi', 'black', 'alex'] # # 八、取出names列表中索引2-10的元素,步長爲2 print("No.08:", names[2:11:2]) # No.08: [['oldboy', 'oldgirl'], '姍姍', 'black', 'black_girl'] # 九、取出names列表中最後3個元素; print("No.09:", names[-3:]) # No.09: ['black', 'alex', 'black_girl'] print("此處爲分隔符0".center(120, '-')) # 十、循環names列表,打印每一個元素的索引值和元素; # 方法01: count = 0 for name in names: print("No.10-1", count, name) count += 1 """ 0 old_driver 1 rain 2 ['oldboy', 'oldgirl'] 3 jack 4 姍姍 5 peiqi 6 black 7 alex 8 black_girl """ print("此處爲分隔符1".center(120, '-')) # 方法02:enumerate(names) 枚舉; print(enumerate(names)) # 直接取索引,<enumerate object at 0x107a17a68> for name in enumerate(names): print("No.10-2", name) # 打印的值是一個小列表 print("此處爲分隔符2".center(120, '-')) """ (0, 'old_driver') (1, 'rain') (2, ['oldboy', 'oldgirl']) (3, 'jack') (4, '姍姍') (5, 'peiqi') (6, 'black') (7, 'alex') (8, 'black_girl') """ for index, name in enumerate(names): print("No.10-3", index, name) # 打印的值不是列表了 print("此處爲分隔符3".center(120, '-')) """ 0 old_driver 1 rain 2 ['oldboy', 'oldgirl'] 3 jack 4 姍姍 5 peiqi 6 black 7 alex 8 black_girl """ # 十一、循環names列表,打印每一個元素的索引值和元素,當索引值爲偶數,把對應的元素改爲-1 for index, name in enumerate(names): if index % 2 == 0: # 表明偶數 names[index] = -1 print("No.11", index, name) # 打印的值不是列表了; print("No.11", names) print("此處爲分隔符".center(120, '-')) # # 十二、names裏有3個2,請返回第2個2的索引值,不要人肉數,要動態找(提示,找到第一個2的位置,在此基礎上再找第2個) # 方法一: names = ['cuixiaozhao', 2, 'cuixiaoshan', 'cuixiaosi', 2, 'cuixiaolei', 1, 3, 4, 2] count = 0 for i in names[names.index(2) + 1:]: if i == 2: print("第二個2的index:", names.index(2) + 1 + count) break count += 1 # 方法二: first_index = names.index(2) # 第一個2的索引值 new_list = names[first_index + 1:] # 從第一個2的位置+1 開始切片,從新賦值給新的列表 second_index = new_list.index(2) # 查詢2 在新的列表中的索引值 last_index = first_index + second_index + 1 # 第一個的索引值+ '第二個的索引值+切片時候的+1' print("第二個2 的index:", last_index) # 1三、現有商品列表以下: products = [['Iphone8', 6888], ['MacPro', 14800], ['小米6', 2499], ['Coffee', 31], ['Book', 80], ['Nike Shoes', 799]] """ 需打印出這樣的格式 ---------商品列表---------- 0. Iphone8 6888 1. MacPro 14800 2. 小米6 2499 3. Coffee 31 4. Book 80 5. Nike Shoes 799 """ print("商品列表".center(60, '-')) for index, product in enumerate(products): # print("%s %s %s" % (str(index) + ".", product[0], product[1])) print("%s. %s %s" % (index, product[0], product[1])) # 1四、寫一個循環,不斷的問用戶想買什麼,用戶選擇一個商品編號,就把對應的商品添加到購物車裏,最終用戶輸入q退出時,打印購物車裏邊的商品列表 shopping_cart = [] while True: for index, product in enumerate(products): print("%s. %s %s" % (index, product[0], product[1])) want = input("您想要買什麼,請輸入對象商品編號: 例<2>,輸入<q>退出 >>") if want.isdigit(): want = int(want) if want > len(products) - 1 and want < 0: print("輸入商品編號錯誤,沒有該編號!!") else: shopping_cart.append(products[want]) print("已經將%s加入購物車" % products[want]) elif want == "q": if len(shopping_cart) > 0: print("您已購買如下商品:") for index, i in enumerate(shopping_cart): print("%s. %s %s" % (index, i[0], i[1])) break else: print("輸入不正確!") continue # 知識補充: # 判斷字符串是不是一個數字; "33".isdigit() # 查看列表的長度; len(names) # break 退出也能夠用標誌位來設置True False 進行循環判斷退出; # 標誌位; flag = True while flag: if 100: pass else: flag = False # 標誌位 設置False 結束循環;
#!/usr/bin/env python # -*- coding:utf-8 -*- # Project: DevelopBasic # Software: PyCharm # DateTime: 2018-10-11 12:17 # File: 14-深淺拷貝.py # __author__: 天晴天朗 # Email: tqtl@tqtl.org "" """ Python3中存在的深淺拷貝; """ # 變量舉例: a = 1 b = a print("a:", a) print("b:", b) print("id(a):", id(a)) print("id(b):", id(b)) print("這裏是分隔符".center(100, '-')) a = 2 print("b:", b) print("a:", a) print("id(b):", id(b)) print("id(a):", id(a)) print("這裏是分隔符".center(100, '-')) # 列表舉例: names = ['cuixiaozhao', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan'] names2 = names print("names:", names) # names: ['cuixiaozhao', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan'] print("names2:", names2) # names2: ['cuixiaozhao', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan'] print("names的id值:", id(names), "names2的id值:", id(names2)) # names的id值: 4422633096 names2的id值: 4422633096 print(id(names[1]), id(names2[1])) # 4560274288 4560274288 names[0] = "崔曉昭" print(names) print(names2) print("這裏是分隔符".center(100, '-')) print("此時的names:", names) # 此時的names: ['崔曉昭', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan'] names_copy2 = names.copy() print("names的淺拷貝之names_copy2:", names_copy2) print("names的id值:", id(names), "names_copy2的id值:", id(names_copy2)) print(id(names[1]), id(names_copy2[1])) # 4480082800 4480082800 print("這裏是分隔符3".center(100, '-')) names.append(['崔天晴', '崔天朗']) names_copy2.append(['cxz', 'cxs']) names_copy3 = names.copy() print(names) print(names2) print(names_copy2) print(names_copy3) """ ['崔曉昭', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan', ['崔天晴', '崔天朗']] ['崔曉昭', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan', ['崔天晴', '崔天朗']] ['崔曉昭', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan', ['cxz', 'cxs']] ['崔曉昭', 'cuixiaoshan', 'cuixiaosi', 'cuixiaolei', 'cuixiaoyan', ['崔天晴', '崔天朗']] """ print(id(names)) print(id(names2)) print(id(names_copy2)) print(id(names_copy3)) """ 4410074760 4410074760 4410074824 4409935048 """ names[-1][0] = "2020" print(names) print(names2) print('-----------------***********--------------------------') print(names_copy2) print(names_copy3) print('-----------------***********--------------------------') print(id(names[-1][0])) print(id(names2[-1][0])) print(id(names_copy2[-1][0])) print(id(names_copy3[-1][0])) """ 4537801168 4537801168 4537800552 4537801168 """ # 不建議使用deepcopy; import copy n4 = copy.deepcopy(names) print(n4) print(names) print('----------------------') names[-1][0] = 19930911 print(names) print(n4) print(id(names[-1][0])) print(id(n4[-1][0]))
s = ‘Hello,beauty!How are you?’git
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/8 5 s = "Hello World!" 6 print(s.capitalize())#Hello world!首字母大寫; 7 print(s.center(50,'*'))#*******************Hello World!******************* 8 print(s.center(50,'-'))#-------------------Hello World!------------------- 9 print(s.count('o'))#全局統計字符o的數量;2; 10 print(s.count('o',0,5))#指定範圍統計字符o的數量;1; 11 print(s.endswith('!'))#返回布爾值True; 12 print(s.endswith('!jfdskl'))#返回布爾值False; 13 s2 = 'a\tb' 14 print(s2)#a、b;默認字符長度; 15 print(s2.expandtabs(20))#a、b中間指定數量的字符長度;; 16 print(s.find('o'))#4 17 print(s.find('ofdjskl'))#-1 18 print(s.find('o',0,5))#4 19 print(s.find('o',0,4))#-1,顧頭不顧尾; 20 print(s.find('W',0,120))#6,顧頭不顧尾; 21 s3 = "my name is {0},i am {1} years old." 22 print(s3.format('TQTL',26))#my name is TQTL,i am 26 years old. 23 s3 = "my name is {name},i am {age} years old." 24 #print(s3.format('TQTL',26))#KeyError: 'name' 25 print(s3.format(name='cuixiaozhao',age=26))#my name is cuixiaozhao,i am 26 years old.
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/8 5 s = "Hello World!" 6 print(s.index('o'))#返回字符的索引值,默認是全局查找:4 7 #print(s.index('o',8,10))#ValueError: substring not found;指定範圍查找; 8 s1 = "1993" 9 print(s1.isalnum())#True,判斷長得像不像數字; 10 s2 = "cxz19930911" 11 print(s2.isalnum())#True; 12 s3 = "cuixiaozhao" 13 print(s1.isalpha())#False; 14 print(s2.isalpha())#False; 15 print(s3.isalpha())#True; 16 s4 = '18.88'#首先它得是字符串,此處不能夠爲s4 = 18.88; 17 s5 ='18'#首先它得是字符串,此處不能夠爲s4 = 18; 18 print(s4.isdecimal())#False; 19 print(s5.isdecimal())#True; 20 print(s4.isdigit())#False; 21 print(s5.isdigit())#True; 22 s6 = "names" 23 print(s.isidentifier())#判斷是否爲合法的變量; 24 print(s4.isidentifier()) 25 print(s6.isidentifier()) 26 print('cxs19920619'.isnumeric())#判斷是否僅有數字在裏面; 27 print('19930911'.isnumeric())#判斷是否僅有數字在裏面; 28 print('19971224'.isprintable())#Linux中一切皆文件,判斷是否是能夠打印,文本文件; 29 print('19971224fdsf'.isprintable())#Linux中一切皆文件,判斷是否是能夠打印,文本文件; 30 print('A B C'.isspace())#判斷是否是空格space空格的意思; 31 print('A BC'.isspace()) 32 print(''.isspace()) 33 print(' '.isspace()) 34 s7 = "Important News" 35 s8 = "HAPPY FAMILY" 36 print(s7.istitle())#新聞標題單詞首字母均爲大寫,判斷是否是title; 37 print(s7.isupper())#判斷是否是全爲大寫; 38 print(s8.isupper())#判斷是否是全爲大寫; 39 names = ['alex','jack','rain'] 40 print(''.join(names))#alexjackrain; 41 print('-'.join(names))#alex-jack-rain; 42 print('*'.join(names))#alex*jack*rain; 43 print('^'.join(names))#alex^jack^rain; 44 s9 = 'Hello World!' 45 s10 = 'hello world!' 46 s11 = 'HELLO WOLRD!' 47 print(s9.ljust(50,'-'))#Hello World!-------------------------------------- 48 print(s9.rjust(50,'-'))#--------------------------------------Hello World! 49 print(s9.upper())#HELLO WORLD! 50 print(s9.lower())#hello world! 51 print(s11.isupper())#True 52 print(s10.islower())#True 53 s12 = '\n hello world!你好 世界 ' 54 print(s12.strip())#hello world!你好 世界 ;去掉左右兩側多餘字符; 55 print(s12.lstrip())#hello world!你好 世界; 56 print(s12.rstrip())#hello world!你好 世界; 57 str_in = 'abcdef' 58 str_out = '!@#$%^' 59 s13 = 'xzabcdsaef' 60 table = str.maketrans(str_in,str_out)#先生成對應關係表; 61 print(table)#{97: 33, 98: 64, 99: 35, 100: 41, 101: 94, 102: 40} 62 print(s13.translate(table))#xz!@#$s!%^; 63 s14 = 'cuixiaozhao' 64 print(s14.partition('o'))#('cuixia', 'o', 'zhao') 65 print(s14.replace('a','MM')) 66 print(s14.replace('a','MM',1))#指定更換的次數; 67 print(s14.rfind('o'))#從右側開始查找; 68 print(s14.rfind('fdsafd'))#從右側開始查找,找不到返回值-1; 69 print(s14.rfind('fdsafd',0,10))#從右側開始查找,指定範圍,找不到返回值-1; 70 #print(s14.rindex('fdsafd',0,10))#從左側開始查找,指定範圍,找不到會報錯:ValueError: substring not found; 71 #print(s14.rindex('o',0,5))#從右側開始查找,指定範圍,找不到會報錯:ValueError: substring not found; 72 print(s14.rindex('o',0,10))#從右側開始查找,指定範圍,返回索引值; 73 s15 = 'Hello World!' 74 print(s15.rpartition('o'))#('Hello W', 'o', 'rld!') 75 print(s15.split('e'))#['H', 'llo World!'] 76 print(s15.split('o'))#['Hell', ' W', 'rld!'] 77 print(s15.split('l'))#['He', '', 'o Wor', 'd!'] 78 print(s15.rsplit('o',1))#['Hello W', 'rld!'],指定次數分割; 79 s16 = 'a\nb\nalex\ncuixiaozhao' 80 print(s16.splitlines())#['a', 'b', 'alex', 'cuixiaozhao']按照行來進行分割; 81 s17 = 'hello world' 82 print(s17.startswith('he'))#True 83 print(s17.startswith('He'))#False 84 print(s17.startswith('fdsk'))#False 85 print(s17.endswith('fdsk'))#False 86 print(s17.endswith('rld'))#True 87 print(s17.endswith('RLD'))#Flase 88 print(s17.swapcase())#HELLO WORLD,小寫變成大寫; 89 print(s17.title())#Hello World,將字符串編程title類型的; 90 print(s17.zfill(20))#000000000hello world,將字符串變成20位長度,不夠的用0填充; 91 #isdigit,replace,find,count,strip,center,split,format,join
names = ('cuixiaozhao','cuixiaosi','cuixiaoshan')程序員
特性:數據庫
1 names = ('cuixiaozhao',['a','b'],1,2,[1,2,3,4,5])#建立names元組; 2 names[1][0]='TQTL'#對names元組中的子列表進行修改; 3 print(names)#('cuixiaozhao', ['TQTL', 'b'], 1, 2, [1, 2, 3, 4, 5])
功能:編程
使用場景:windows
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/8 7:25 5 #需求:存儲公司60~70人的姓名、年齡、性別、手機號、部門、崗位、家鄉.... 6 names = [ 7 ['Alex',26,'技術部','工程師',13651054608], 8 ['Shanshan',25,'公關部','野模',13374245235], 9 ['龍婷',24,'設計部','UI',13824234452], 10 ] 11 #print(names.index('龍婷'))#ValueError: '龍婷' is not in list; 12 print(names.index(['龍婷',24,'設計部','UI',13824234452]))#媽的,我都知道這麼多信息了,我查詢它(索引2)有病呀! 13 info = {}#定義一個空字典; 14 info = { 15 '龍婷':[24,'design','UI',13811221893], 16 'shanshan':[25,'PR','wild model',13681590211] 17 } 18 print(info['龍婷'])#返回值:[24, 'design', 'UI', 13811221893] 19 #修改信息 20 mod = info['龍婷'][1]='設計部' 21 print(mod)#設計部 22 print(info)#{'龍婷': [24, '設計部', 'UI', 13811221893], 'shanshan': [25, 'PR', 'wild model', 13681590211]} 23 #字典的查找速速快的緣由,由於hash查找速度快; 24 print(hash('龍婷'))#哈希值:7073574030525645556; 25 print(hash('Shanshan'))#哈希值:232415886153887154; 26 numbers = [13334,-32424,25532,2364] 27 numbers.append(3355) 28 numbers.append(123334) 29 print(numbers)#[13334, -32424, 25532, 2364, 3355, 123334] 30 numbers.sort(); 31 print(numbers)#[-32424, 2364, 3355, 13334, 25532, 123334] 32 #經過折半查找,就可很快滴查找到值(二分查找);
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/8 21:51 5 info = { 6 'stu1101':'TengLan Wu', 7 'stu1102': 'LongZe Luola', 8 'stu1103': 'XiaoZe Maliya' 9 }#定義了字典info,如何判斷,{}、[]、()的區別; 10 info['stu1104'] = "蒼井空"#字典的添加,有則從新賦值,無則新增一鍵值對; 11 print(info)#{'stu1101': 'TengLan Wu', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': '蒼井空'} 12 #字典的修改; 13 info['stu1101'] = "武藤蘭"#經過鍵值,進行字典的從新賦值,進行相應的修改; 14 print(info)#{'stu1101': '武藤蘭', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': '蒼井空'} 15 #字典的查詢; 16 print("stu1102" in info)#True 17 print(info.get('stu1102'))#LongZe Luola; 18 print(info.get('stu110211111111'))#None; 19 print(info['stu1102'])#LongZe Luola;不推薦使用,若是不存在會報錯! 20 #print(info['stu1102-11111111'])#KeyError: 'stu1102-11111111',因此通常會優先使用字典中的get方法; 21 #print(info.pop())#TypeError: pop expected at least 1 arguments, got 0 22 print(info.pop('stu1101'))#pop方法刪除字典元素,有返回值:武藤蘭; 23 print(info)#{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': '蒼井空'} 24 #字典的添加 25 info[4] = 'Number1'#增長; 26 info[3] = 'Number2' 27 info[2] = 'Number3' 28 info[1] = 'Number4' 29 print(info)#{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': '蒼井空', 4: 'Number1', 3: 'Number2', 2: 'Number3', 1: 'Number4'} 30 #字典的刪除操做; 31 print(info.popitem())#字典是無序的,隨機刪除字典中的元素;(1, 'Number4'); 32 print(info.popitem())#字典是無序的,隨機刪除字典中的元素;(2, 'Number3'); 33 for i in range(100): 34 info[i]= 'Number'+(str(i))#for循環向字典中增添數據; 35 print(info.popitem())#popitem是無序隨機刪除; 36 print(info.popitem()) 37 print(info.popitem()) 38 print(info.popitem()) 39 print(info.popitem()) 40 print(info.popitem()) 41 del info[56]#使用字典的del 方法進行刪除; 42 #多級字典的嵌套——字典裏面套字典; 43 av_catalog = { 44 "歐美":{ 45 "www.youporn.com": ["不少免費的,世界最大的","質量通常"], 46 "www.pornhub.com": ["不少免費的,也很大","質量比yourporn高點"], 47 "letmedothistoyou.com": ["可能是自拍,高質量圖片不少","資源很少,更新慢"], 48 "x-art.com":["質量很高,真的很高","所有收費,屌絲請繞過"] 49 }, 50 "日韓":{ 51 "tokyo-hot":["質量怎樣不清楚,我的已經不喜歡日韓範了","據說是收費的"] 52 }, 53 "大陸":{ 54 "1024":["所有免費,真好,好人一輩子平安","服務器在國外,慢"] 55 } 56 } 57 #字典的修改; 58 av_catalog["大陸"]["1024"][1] = "不要緊,可使用爬蟲爬取下來,後續咱們會講爬蟲課程的,注意認真聽講哦srapy"#多級字典的逐級查找; 59 print(av_catalog) 60 #{'歐美': {'www.youporn.com': ['不少免費的,世界最大的', '質量通常'], 'www.pornhub.com': ['不少免費的,也很大', '質量比yourporn高點' 61 # ], 'letmedothistoyou.com': ['可能是自拍,高質量圖片不少', '資源很少,更新慢'], 'x-art.com': ['質量很高,真的很高', '所有收費,屌比請繞過 62 # ']}, '日韓': {'tokyo-hot': ['質量怎樣不清楚,我的已經不喜歡日韓範了', '據說是收費的']}, '大陸': {'1024': ['所有免費,真好,好人一輩子平安 63 # ', '不要緊,可使用爬蟲爬取下來,後續咱們會講爬蟲課程的,注意認真聽講哦srapy']}} 64 #字典的其餘方法; 65 info.clear()#針對字典進行清空操做,字典級別的操做; 66 print(info)#{}空字典; 67 #info['alex':[24,'IT'],'rain':[24,'HR'],'jack':22]# info['alex':[24,'IT'],'rain':[24,'HR'],'jack':22] TypeError: unhashable type: 'slice' 68 info = {'alex':[24,'IT'],'rain':[24,'HR'],'jack':22} 69 print(info) 70 print(info.keys())#dict_keys(['alex', 'rain', 'jack']) 71 print(info.values())#dict_values([[24, 'IT'], [24, 'HR'], 22]) 72 print(info.items())#dict_items([('alex', [24, 'IT']), ('rain', [24, 'HR']), ('jack', 22)]) 73 dic2 = {1:2,2:3,'jack':[22,'Jack Ma','Alibaba CEO']} 74 print(info)#{'alex': [24, 'IT'], 'rain': [24, 'HR'], 'jack': 22} 75 info.update(dic2)#相似於list中的extend方法,2個字典的間的拓展操做; 76 print(info)#{'alex': [24, 'IT'], 'rain': [24, 'HR'], 'jack': [22, 'Jack Ma', 'Alibaba CEO'], 1: 2, 2: 3}#若是有對應值就覆蓋,沒有則建立; 77 print(info.setdefault(2,'New 2'))#返回值3,若是有鍵2,則返回2的值; 78 print(info.setdefault('test','New 2'))#返回值New 2,若有沒有,則返回; 79 print(info) 80 print(info.fromkeys(['A','B','C']))#{'A': None, 'B': None, 'C': None} 81 print(info.fromkeys(['A','B','C'],'alex'))#{'A': 'alex', 'B': 'alex', 'C': 'alex'}實際應用先生成空字典,再批量插入值; 82 #與list類似,dict也能夠循環; 83 for k in info: 84 print(k) 85 print(k,info[k])#最經常使用的字典循環方法; 86 #下方不高能,不建議使用,效率是生產力的第一保障! 87 for k,v in info.items():#低效率,先把字典轉化成列表,再循環遍歷,拒絕使用吧! 88 print(k,v)
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/9 5:10 5 iphone7 = ['alex','rain','jack','old_driver'] 6 iphone8 = ['alex','shanshan','jack','old_boy'] 7 both_list = [] 8 #如何找出同時買了IPhone7和8的人?! 9 for name in iphone7:#先循環一個列表,嵌套; 10 if name in iphone8: 11 both_list.append(name) 12 print(both_list)#['alex', 'jack'] 13 #對比兩個數據集合的操做-交集、差集、並集; 14 #集合的建立方式; 15 dic1 = {}#此處是字典; 16 print(type(dic1))#<class 'dict'> 17 print(type({}))#<class 'dict'> 18 dic2 = {1,2,3,4,5}#此處是集合; 19 print(type(dic2))#<class 'set'>,數據類型集合set 20 dic3 = {1,2,3,4,2,3,6} 21 print(dic3)#{1, 2, 3, 4, 6}集合自動去重; 22 lis1= [1,2,3,4,5,2,3] 23 print(lis1)#[1, 2, 3, 4, 5, 2, 3] 24 print(set(lis1))#{1, 2, 3, 4, 5}將列表轉化爲集合set; 25 print(type(set(lis1)))#<class 'set'>,能轉化list和元組; 26 #集合的方法; 27 #增長; 28 dic4 = {1,2,3,4,5} 29 dic4.add(2)#增長一個已存在的值; 30 print(dic4)#{1, 2, 3, 4, 5} 31 dic4.add(6)#增長一個未存在的值; 32 print(dic4)#{1, 2, 3, 4, 5, 6} 33 #print(help(dic4.pop()))查看字典的幫助信息; 34 dic4.pop()#集合是無序的,隨機刪除一個元素,無索引的概念; 35 print(dic4)#隨機刪除一個元素後的結果輸出{2, 3, 4, 5, 6}; 36 #刪除集合中指定的元素; 37 dic4.remove(6) 38 print(dic4)#{2, 3, 4, 5} 39 #discard方法;相似於字典中的get方法; 40 #dic4.remove(6)#KeyError: 6,使用remove方法,刪除集合中不存在的元素,會出現報錯信息; 41 dic4.discard(6)# 42 print(dic4)#{2, 3, 4, 5},使用discard方法,刪除集合中不存在的元素,不會出現報錯信息,一些場景推薦使用; 43 dic4.update([10,12,15,1,2,3,4,5])#往集合中拓展多個元素,add只能一次增長一個,相似於list中的extend方法和字典中的update方法; 44 print(dic4)#{1, 2, 3, 4, 5, 10, 12, 15} 45 #清空set中的內容; 46 dic4.clear() 47 print(dic4)#set()
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/9 5:39 5 #取出交集; 6 iphone7 = {'alex','rain','jack','old_driver'} 7 iphone8 = {'alex','jack','shanshan','old_boy'} 8 print(iphone7.intersection(iphone8))#{'jack', 'alex'},取出二者的交集; 9 print(iphone7&iphone8)#{'jack', 'alex'},此刻,&符號等價於intersection方法; 10 #取出差集; 11 print(iphone7.difference(iphone8))#{'old_driver', 'rain'},買了iphone7卻沒有買iPhone8的人; 12 print(iphone7-iphone8) 13 print(iphone8.difference(iphone7))#{'shanshan', 'old_boy'},買了iphone8卻沒有買iPhone7的人; 14 print(iphone8-iphone7); 15 #取出並集; 16 print(iphone8.union(iphone7)) 17 print(iphone7.union(iphone8)) 18 print(iphone7|iphone8) 19 print(iphone8|iphone7) 20 #以上4者等價{'jack', 'old_boy', 'shanshan', 'old_driver', 'rain', 'alex'},買了iphone7或者iPhone8的人 21 #對稱差集-需求:取出二者不想交的部分,只買了iPhone7或iphone8的人; 22 s = {1,2,3,4} 23 s2 = {2,3,5,6} 24 print(s.symmetric_difference(s2))#{1, 4, 5, 6} 25 print(s2.symmetric_difference(s))#{1, 4, 5, 6} 26 print(iphone8.symmetric_difference(iphone7)) 27 print(iphone7.symmetric_difference(iphone8)) 28 #以上4者等價{'old_driver', 'shanshan', 'old_boy', 'rain'},買了iphone7或者iPhone8的人 29 #子集和超集; 30 s2.add(1) 31 s2.add(4) 32 print(s2)#{1, 2, 3, 4, 5, 6} 33 print(s)#{1, 2, 3, 4} 34 print(s.issubset(s2))#True,判斷集合是否是被其餘集合包含,等同於 s <=s2; 35 print(s.issuperset(s2))#Flase判斷集合是否是包含其餘集合,等同於 s >=s2; 36 print(s2.issubset(s))#Flase; 37 print(s2.issuperset(s))#True; 38 #超集和子集可使用> 或<符號; 39 #若是集合中的數據量特別大,可使用s.isdisjoint()判斷是否不相交; 40 print(s.isdisjoint(s2))#False; 41 print(s2.isdisjoint(s))#False,返回False說明兩者相交; 42 s3 = {1,2,3,4,-1,-2} 43 s4 = {1,2,3,4,5,6} 44 s3.difference_update(s4)#將s3與s4差集的結果賦值給s3,{-2, -1} 45 print(s3) 46 # s4.difference_update(s3) 47 # print(s4) 48 49 s3 = {1,2,3,4,-1,-2} 50 s4 = {1,2,3,4,5,6} 51 s3.intersection_update(s4)#不經常使用,把交集的結果賦值給s3,{1, 2, 3, 4} 52 print(s3) 53 54 55 s3 = {1,2,3,4,-1,-2} 56 s4 = {1,2,3,4,5,6} 57 s4.intersection_update(s3)#不經常使用,把交集的結果賦值給s4,{1, 2, 3, 4} 58 print(s4)
1 #! /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #__author__ = "tqtl" 4 # Date:2018/5/9 6:14 5 6 #10進制轉換八、16進制的語法 7 print(oct(1))#0o1 10進制轉換8進制,以0o開頭,逢7進1 8 print(oct(2))#0o2 9 print(oct(3))#0o3 10 print(oct(7))#0o7 11 print(oct(8))#0o10 12 print(oct(64))#0o100 13 print('-------------------') 14 print(hex(1))#0x1 10進制轉換16進制,以0x開頭,逢16進1 15 print(hex(3))#0x3 16 print(hex(9))#0x9 17 print(hex(10))#0xa 18 print(hex(11))#0xb 19 print(hex(15))#0xf 20 print(hex(16))#0x10 21 print(hex(1115))#0x45b
二進制數與十六進制數之間如何互相轉換https://jingyan.baidu.com/album/47a29f24292608c0142399cb.html?picindex=1api
http://www.cnblogs.com/alex3714/articles/7550940.html服務器
過渡句:因爲每一個國家都有本身的一套字符編碼,因此其對應關係也涵蓋了本身國家的字符,可是以上編碼存在必定的「侷限性」,即:僅涵蓋本國字符,無其餘國家字符的對應關係。由此,應運而生了「萬國碼」,他涵蓋了全球全部文字和二進制的對應關係。網絡
1)Unicode的做用;
1.支持全球各個國家的語言,每一個國家能夠再也不使用本身以前的舊編碼了;
2.Unicode包含了跟全球全部國家編碼的映射關係;
Unicode雖然解決了字符和二進制的對應關係,可是使用unicode表示一個字符,太浪費空間。比原來ASCII碼存儲多了一倍額空間;因爲計算機內存比較大而且字符串在內容中表示不會特別大,因此內容能夠用unicode來處理,可是「存儲」和「網絡傳輸」時,數據量就顯得特別大,好比,我在「阿里雲」上購買的ECS服務器的帶寬是「按量付費」的,使用ASCII碼,每個月繳納1w元,使用Unicode就得繳納2w元,真是「是可忍孰不可忍」呀!
2)Unicode的缺點
1.使用unicode表示字符,多佔用一倍的存儲空間;
2.在存儲和網絡傳輸過程當中,耗費資源;
這個世界就是在人們的智慧中不斷髮展壯大的。爲了解決存儲和網絡傳輸的問題,再次應運而生了Unicode Transformation Format,學術名UTF,即:對unicode中的存儲進行轉換,以便於在存儲和網絡傳輸時節省空間;
總結:UTF 是unicode編碼設計的一種在存儲和傳輸時節省空間的編碼方案。
http://www.cnblogs.com/alex3714/articles/7550940.html
要注意的是,存到硬盤上時是以何種編碼存的,再從硬盤上讀出來時,就必須以何種編碼讀,要否則就亂了。。。
http://www.unicode.org/charts/PDF/U4E00.pdf
1)亂碼是正常的,不亂纔不正常,由於只有2種狀況,windows上顯示纔不會亂;
雖然說打印的是路飛,但直接調用變量s,看到的倒是一個個的16進製表示的「二進制字節」,咱們如何稱呼這樣的數據呢?直接叫「二進制」嗎?能夠的,但相比與0101000111,這個「數據串」在表現形式上又把2進制轉成了16進制來表示,這是爲何呢?爲的就是讓人們看起來更可讀。咱們稱之爲bytes類型,即字節類型。它把8個二進制一組稱爲byte,用16進制來表示。
Python2中的字符串更應該稱爲字節串,咱們經過存儲方式就能看出來,但Python2中還有一個類型是bytes。在Python2做用,bytes==str,就是這麼回事。
二、圖片沒有字符編碼;
爲了表示圖片、視頻等二進制格式的數據類型;
以unicode編碼;
掌握了編碼以前的關係後,挨個排錯就行了。