一、list爲是有序的,所以又下標,能夠多多層嵌套php
tuple和list差很少,可是tuple一旦建立第一級就不能修改,好比其中一個元素爲list,則改list能夠被修改html
二、list、tuple方法java
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen import copy animal = ['dog', 'cat', 'tiger', 'fish', 'fish', 'lion', 'dog'] vegetables = ['potato', 'tomato', 'bean'] tuple_test = (1, 2, [1, 3, 6]) tuple_test[2][2] = 11 # 元祖不能修改是指第一級 可是裏面的list能夠被修改 print(tuple_test) for i, v in enumerate(animal): # enumerate同時列出數據和數據下標 print(i, v) print(animal.count('dog')) # 統計出現的次數 animal.append('horse') # 列表後面追加 something = animal.copy() # 只copy第一級,若是第二級是list則只是引用,修改其中一個第二級的值兩個都會修改 something2 = copy.copy(animal) # copy 和 list.copy是同樣的 something3 = copy.deepcopy(animal) # 徹底複製一份,不引用 something.extend(vegetables) # 合併兩個list print(something) print(something.index('tomato')) # 列出tomato的索引 del something[-3] # 通用刪除法 something.pop(-3) # 刪除索引爲-3的對象,默認最後一個 something.append('cabbage') print(something) something.remove('dog') # 刪除指定元素 print(something) something.insert(1, 'soy') # 在指定位置插入元素 print(something) something.reverse() # 反轉列表的順序 print(something) something.sort() # 對列表進行排序,默認ASCII進行排序 key參數能夠指定函數返回的值來排序 print(something) print(something[0:4]) # 切片 print(something[-3:-1]) # 若是是負數下標,可是仍是按從左往右切片 print(something[0:4:2]) # 取0到4 每隔兩個取一個
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen name = ' my name is glen HHH,\t I am {age} \r\n years old, hello everyone ! \n' print(name.count('y')) # 統計在字符中出現的次數 print(name.capitalize()) # 首字母大寫 print(name.casefold()) # 大寫全變小寫 print(name.center(50, '-')) # 一共輸出50個字符,若是不夠就在兩邊補足‘-’,str放中間 name_b_gbk = name.encode(encoding='gbk') # 將str編碼爲bytes的二進制形式,解碼也須要對應的字符集,默認utf-8 print(name_b_gbk) print(name_b_gbk.decode(encoding='gbk')) # 須要對應的解碼字符集 print(name.endswith('!')) # 判斷已什麼字符結尾,返回True或者False print(name.expandtabs(20)) # 將 table=製表符=\t 轉換爲多長的空格 print(name.format(age=26)) # {}中預先設置的字符轉換爲變量值 print(name.format_map({'age': '20'})) # 和format相似,能夠直接使用字典進行賦值 print(name.find('I')) # 從左到右查詢,返回第一個匹配的字符下標 ASCII 表區分大小寫 print(name.rfind('l')) # 從右往左查詢,返回第一個匹配字符的下表 print(name.index('i')) # 返回字符i所在的索引 number = '123' print(number.isalnum()) # 判斷字符串裏面的每一個字符是否爲純數字 小數點爲字符,返回True or False alpha = 'Abc' print(alpha.isalpha()) # 判斷是否爲純字母, 返回True or False print(name.isdecimal()) # 不經常使用,檢查字符串是否只包含十進制字符。這種方法只存在於unicode對象。 注意:定義一個十進制字符串,只須要在字符串前添加 'u' 前綴便可。 print(number.isdigit()) # 判斷是否爲十進制整數 print(alpha.islower()) # 判斷字母是否所有爲小寫 print(name.isnumeric()) # 不經常使用 檢測字符串是否只由數字組成。這種方法是隻針對unicode對象。注:定義一個字符串爲Unicode,只須要在字符串前添加 'u' 前綴便可 print(alpha.isidentifier()) # 檢測一個一段字符串是否能夠做爲變量,即符合變量命名規則 print(alpha.isprintable()) # 不經常使用 判斷是否爲可打印字符,linux中設備也是文件形式,此時爲不可打印 spa = ' ' print(spa.isspace()) # 判斷是否爲純空格 print(name.istitle()) # 判斷是否爲標題 即每一個單詞的第一個字符爲大寫 upper = 'A b' print(upper.isupper()) # 判斷字符串中全部的字母是否都爲大寫 L_join = ['1', '2', '3'] print('-'.join(L_join)) # 輸出爲 1-2-3 將序列的元素以指定的字符串進行鏈接 print(upper.ljust(50, '-')) # 返回一個字符串,共50個字符,左對齊,若是不夠用‘-’補足 print(upper.ljust(50, '-')) # 返回一個字符串,共50個字符,右對齊,若是不夠用‘-’補足 print(name.lower()) # 把全部的字母所有轉爲小寫 print(name.strip('\n')) # 去掉先後換行符\n, 默認是去掉去空格 print(name.lstrip()) # 去掉前面空格 print(name.rstrip('\n')) # 去掉後面換行符 p = str.maketrans('is', '11') # 預設i 》1,s》1,而後對name進行處理,須要一一對應 print(name.translate(p)) print(name.partition('is')) # 指定字符串進行分割,第一個is進行分割,返回三元組,分別爲is前的字符,is,is後的字符 print(name.split('H')) # 按指定字符進行分割,連續指定字符則返回''元素,默認空格處理時已經對''進行排除,指定字符沒有排除 print(name.splitlines()) # 不論Windows仍是linux,若是是多行字符,則按行爲元素返回list print(name.startswith(' ')) # 判斷是否以指定字符開頭,返回True or False print(name.swapcase()) # 大寫轉小寫,小寫轉大寫 print(name.title()) # 轉爲標題 print(name.upper()) # 轉爲大寫 print(name.zfill(100)) # 返回指定長度的字符串,原字符串右對齊,前面填充0。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen info = dict(st1='java', st2='C++', st3='python') print(info) info['st1'] = 'python' # st1修改成python info['st4'] = 'java' # 添加key爲st4,值爲java info.setdefault('st5', 'php') # 若是鍵不存在於字典中,將會添加鍵並將值設爲默認值。若是又則不修改 # del info['st1'] # 通用刪除 print(info.pop('st1')) # 刪除給定的key,並返回值,必須給定key print(info.popitem()) # 因爲dict是無序的,所以是隨機刪除 並返回key和值的遠足 # info.clear() # 清空字典 info2 = info.copy() # 返回一個字典的淺複製 print(info2) info3 = dict.fromkeys([1, 2, 3], ['water', 'fire']) # 經過一個列表生成默認dict,默認值爲hello, print(info3) info3[1][0] = 'soil' # 這裏有個坑,若是默認值是list這種,則是引用,一改全改 print(info3) print(info.get('st2')) # 經過get來安全的獲取值,若是沒有返回None,不會拋異常 # print(info['st1']) # 直接取若是沒有key st1 則會拋 KeyError 異常 info.items() # 函數以列表返回可遍歷的(鍵, 值) 元組數組。for 循環取值時不建議使用,效率過低,直接遍歷key就行 print(info.keys()) # 返回該字典全部的key info4 = dict(st3='html', st10='c', st11='shell') info.update(info4) # 將兩個dict合併,由則更新,沒有則添加 print(info) print(info.values()) # 函數以列表返回字典中的全部值。 # 循環dict 這樣取值比items效率高 for i in info: print(i, info[i])
# 快速建立dict的方法 msg = 'name glen age 26 work it' msg_list = msg.split() print(msg_list) msg_dict = dict(zip(msg_list[0::2], msg_list[1::2])) print(msg_dict) # {'name': 'glen', 'age': '26', 'work': 'it'} >>>a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) # 打包爲元組的列表 [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) # 元素個數與最短的列表一致 [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) # 與 zip 相反,*zipped 可理解爲解壓,返回二維矩陣式 [(1, 2, 3), (4, 5, 6)]
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen menu = { '四川': { '巴中': ['通江縣', '南江縣'], '成都': ['雙流區', '錦江區', '武侯區'] }, '浙江': { '杭州': ['臨安區', '西湖區'], '寧波': ['鄞州區', '奉化市'] } } current_menu = menu layers = [menu] exit_flag = False while not exit_flag: for k in current_menu: print(k) choice = input('please enter:') if choice in current_menu and len(layers) < 3: current_menu = current_menu[choice] layers.append(current_menu) elif choice == 'b' and len(layers) > 1: layers.pop(-1) current_menu = layers[-1] elif choice == 'q': exit_flag = True else: print('input error, retype..') else: print('Browse the end...')
5、練習python
購物車程序linux
一、用戶入口:商品信息存在文件裏面,已購商品和餘額記錄在文件裏面,啓動後直接讀取。git
二、商家入口:能夠添加商品,修改商品價格。shell
文件:windows
一、user 用戶信息,第一行是購買到的商品,第二行爲餘額api
tv phone refrigerator數組
30000
二、goods 商品文件格式,商品名稱 價格 總數
tv 3000 4
phone 5000 5
refrigerator 4000 2
radio 500 10
用戶接口:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen goods = {} info_user = {} with open('goods', 'r') as f: for line in f.readlines(): list_line = line.split() name0 = list_line[0] price1 = list_line[1] amount2 = list_line[2] goods[name0] = [name0, int(price1), int(amount2)] with open('user', 'r') as f: file_all = f.read().splitlines() user_goods = file_all[0].split() user_balance = file_all[1] info_user['user_goods'] = user_goods info_user['balance'] = int(user_balance) print(info_user) print(goods) exit_flag = False while not exit_flag: print('order', 'name', 'amount') for i in goods: print(i, goods[i][1], goods[i][2]) choice = input('please choice product:') if choice in goods and info_user['balance'] >= goods[choice][1]: info_user['balance'] -= goods[choice][1] info_user['user_goods'].append(choice) goods[choice][2] -= 1 if goods[choice][2] < 1: goods.pop(choice) # print('you balance is', info_user['balance']) print('\033[31;1myou balance is', info_user['balance'], '\033[0m') elif choice in goods: print('\033[31;1myour balance is inadequate...\033[0m') print('\033[31;1myou balance is', info_user['balance'], '\033[0m') elif choice == 'q': exit_flag = True else: print('your enter error...') else: print(goods) print(info_user) print('you balance is', info_user['balance']) with open('goods', 'w') as f: for i in goods: line = ' '.join([str(k) for k in goods[i]]) f.write(line+'\n') print('your goods:', info_user['user_goods']) with open('user', 'w') as f: line_goods = ' '.join([str(k) for k in info_user['user_goods']]) f.write(line_goods+'\n') line_balance = str(info_user['balance']) f.write(line_balance+'\n') print('exit.................')
商戶接口
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen # 定義將product_all字典裏面的全部商品寫入文件的函數 def add_pro(product2): with open('goods', 'w') as f: for k in product2: line2 = ' '.join(product2[k].values()) f.write(line2 + '\n') product = {} # 沒批次添加的商品,一級 product_all = {} # 全部商品,二級字典 exit_flag = False # 是否退出輸入標誌 product_attr = ('pro_name', 'pro_price', 'pro_amount') # 能夠添加的商品屬性 # 從文件讀取全部的商品 with open('goods', 'r') as f: for line in f.readlines(): list_line = line.split() for k, v in enumerate(product_attr): product[v] = list_line[k] product_all[list_line[0]] = product.copy() product.clear() while not exit_flag: for arg in product_attr: user_input = input('\033[31;1madd product {arg}:\033[0m'.format(arg=arg)) if user_input == 'q': exit_flag = True break elif user_input == 'p': for x in product_all: print(x, product_all[x]['pro_price'], product_all[x]['pro_amount']) break elif user_input != 'pro_name' and user_input in product_attr: if not user_input.isdigit(): print('{arg} is number...'.format(arg=arg)) exit_flag = True break else: product[arg] = user_input if len(product) == 3: product_all[product['pro_name']] = product.copy() print('add {pro_name} successful....'.format(pro_name=product['pro_name'])) product.clear() else: add_pro(product_all) print('your add products:', [i for i in product_all])
6、文件操做
打開文件的模式有:
"+" 表示能夠同時讀寫某個文件
"U"表示在讀取時,能夠將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)
"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)
其餘操做
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen f = open('aaa', 'r+', encoding='utf-8') # f.write() # 寫入文件 # f.readline() # 讀取一行,指針位置下以一行到第二行 # f.readlines() # 讀取所有文本,根據行來生成一個列表 # result = f.read() # 讀取所有類容,返回str # f.close() # 關閉文件 print(f.name) # 讀取文件名字自己 print(f.encoding) # 查看編碼格式 print(f.errors) # 異常相關 f.fileno() # 返回文件描述符 較少使用 f.isatty() # 若是鏈接到一個終端設備返回 True,不然返回 False。 如屏幕的標準輸出,也能夠算寫入 f.flush() # 刷新,將在緩存裏面的輸入當即刷新到磁盤 f.tell() # 返回當前指針的位置,通常以字符數計算 f.seek(0) # 設置指針位置,0標識從頭開始讀起,對寫入文件不起做用,若是在已有數據中直接插入會覆蓋磁盤當前位置的數據,所以不能插入 f.readable() # 判斷文件是不是以可讀模式打開的,是否可讀 f.seekable() # 若是文件支持隨機存取 f.truncate(20) # 從指針位置截取20個字符,若是沒有指定大寫截取剩餘全部字符 f.writable() # 是否可寫模式打開 f.writelines(['hell\n', 'sky']) # 寫入一序列的字符串 參數能夠位list,須要指定換行,
7、練習
程序練習
程序1: 實現簡單的shell sed替換功能
程序2:修改haproxy配置文件
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen ha_format = ('global', 'defaults', 'listen', 'frontend', 'backend') index_ha = {} list_tmp = [] ha_dict = {} # 將文件按行讀取到list with open('haproxy', 'r', encoding='utf-8') as f1: ha_all = f1.readlines() # 獲取每段配置項開始位置 for key in ha_format: key_1 = {} for n, sig in enumerate(ha_all): if key in sig and not sig.startswith(' '): key_1['start'] = n list_tmp.append(n) index_ha[key] = key_1 # 獲取每段配置項結束位置 for key in ha_format: start_index = index_ha[key]['start'] index_tmp = list_tmp.index(start_index) if index_tmp+1 < len(list_tmp): index_ha[key]['end'] = list_tmp[index_tmp+1] else: index_ha[key]['end'] = len(ha_all) print(index_ha) # 將文件list轉換位dict for key in ha_format: ha_dict[key] = {} ha_dict[key]['record'] = {} for n, line in enumerate(ha_all[index_ha[key]['start']:index_ha[key]['end']]): line_list = line.split() if n == 0: if len(line_list) < 2: ha_dict[key][key] = '' else: ha_dict[key][key] = ' '.join(line_list[1:]) else: if len(line_list) == 0: break elif len(line_list) < 2: ha_dict[key]['record'][line.split()[0]] = '' else: ha_dict[key]['record'][line.split()[0]] = ' '.join(line.split()[1:]) print(ha_dict) # 將配置文件dict寫入文件 def write_to_file(ha_dict, ha_format): with open('haproxy2', 'w', encoding='utf-8') as f2: for key in ha_format: line1 = '{key} {par}'.format(key=key, par=ha_dict[key][key]) print(line1) f2.write(line1+'\n') for index in ha_dict[key]['record']: line2 = '\t\t' + index + ' ' + ha_dict[key]['record'][index] f2.write(line2 + '\n') print('\t\t{index} {line2}'.format(index=index, line2=line2)) end_flag = False while not end_flag: item = input('>>') if item in ha_dict: print('{item} {value}'.format(item=item, value=ha_dict[item][item])) for index in ha_dict[item]['record']: print('\t\t' + index + ' ' + ha_dict[item]['record'][index]) elif item == 'q': end_flag = True elif item == 'a': print('add item...') else: print('enter wrong...')