python之旅--數據類型
阿新 • • 發佈:2018-05-20
NPU line shopping 數值 沒有 直接 isl 深圳 導入
列表操作
1 >>> info = [1,2,‘a‘,‘b‘,‘python‘] 2 >>> print(info) 3 [1, 2, ‘a‘, ‘b‘, ‘python‘] 4 >>> print(info[0],info[2]) 5 1 a 6 >>> print(info[1:3]) #切片 7 [2, ‘a‘] 8 >>> print(info[3]) 9 b 10 >>> print(info[-1]) #取最後一個 11 python 12 >>> print(info[-2:]) #取最後兩個值 從左到右 省略掉最後面的 13 [‘b‘, ‘python‘] 14 >>> print(info[:3]) #前面是零可以省略 15 [1, 2, ‘a‘] 16 >>> #追加 插入 17 ... info.append("c") 18 >>> print(info) 19 [1, 2, ‘a‘, ‘b‘, ‘python‘, ‘c‘] 20 >>> info.insert(4,"d") 21 >>> print(info) 22 [1, 2, ‘a‘, ‘b‘, ‘d‘, ‘python‘, ‘c‘] 23 >>> #刪除 24 ... info.remove("a") 25 >>> print(info) 26 [1, 2, ‘b‘, ‘d‘, ‘python‘, ‘c‘] 27 >>> del info[1] #按下標刪除 28 >>> print(info) 29 [1, ‘b‘, ‘d‘, ‘python‘, ‘c‘] 30 >>> info.pop() #刪除最後一個 31 ‘c‘ 32 >>> print(info) 33 [1, ‘b‘, ‘d‘, ‘python‘] 34 >>> #查詢位置 35 ... print(info.index("python")) 36 3 37 >>> #統計 38 ... print(info.count("b")) 39 1 40 #擴展 41 >>> info2 = [3,"e"] 42 >>> info.extend(info2) 43 >>> print(info) 44 [1, ‘b‘, ‘d‘, ‘python‘, 3, ‘e‘] 45 #刪除變量 46 >>> del info2
深淺copy
1 >>> import copy #導入copy模塊 2 >>> list1 = ["a","b",["c","d"],"java"] #列表中可以嵌套列表 3 >>> print(list1) 4 [‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘java‘] 5 >>> list2 = list1.copy() #淺copy 6 >>> print(list2) 7 [‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘java‘] 8 >>> list3 = copy.deepcopy(list1) #深copy 需要導入copy模塊 9 >>> print(list3) 10 [‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘java‘] 11 >>> list4 = list1 #賦值 12 >>> print(list4) 13 [‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘java‘] 14 >>> list1[3] = "python" #修改列表父對象 15 >>> list1[2][0] = "v" #修改列表子對象 16 >>> print(list1) #打印修改後的列表 17 [‘a‘, ‘b‘, [‘v‘, ‘d‘], ‘python‘] 18 >>> print(list2) #只拷貝父對象,不會拷貝對象的內部的子對象 子對象會改變 19 [‘a‘, ‘b‘, [‘v‘, ‘d‘], ‘java‘] 20 >>> print(list3) #完全復制 拷貝對象及其子對象 21 [‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘java‘] 22 >>> print(list4) 23 [‘a‘, ‘b‘, [‘v‘, ‘d‘], ‘python‘]
#聯名賬戶 賬戶中余額都可以看到 賬戶名不改變 >>> person = ["name",["saving",100]] >>> p1 = person[:] >>> p2 = person[:] >>> p1[0] = "A" >>> p2[0] = "B" >>> p1[1][1] = 50 #兩個人都可以看到賬號余額改變 >>> print(p1) [‘A‘, [‘saving‘, 50]] #各自的賬號名 余額同步改變 >>> print(p2) [‘B‘, [‘saving‘, 50]]
元組
存一組數據,一旦創建便不能修改,所以又叫只讀列表
只有兩個方法:index 和 count
>>> names = (‘a‘,‘b‘,‘c‘,‘a‘) >>> names.count(‘a‘) 2 >>> names.index(‘a‘) 0 >>> names.index(‘a‘,2) 3
程序練習
程序:購物車程序
需求:
1.啟動程序後,讓用戶輸入工資,然後打印商品列表。
2.允許用戶根據商品編號購買商品。
3.用戶選擇商品後,檢測余額是否夠,夠直接扣錢,不夠提醒。
4.可隨時退出,退出時,打印已購買商品和余額。
product_list = [ (‘iphone‘,5800), (‘mac pro‘,12000), (‘bike‘,800), (‘watch‘,10600), (‘coffee‘,33) ] shopping_list = [] salary = input("input your salary:") if salary.isdigit(): #判斷是否整數 salary = int(salary) while True: #for item in product_list: #print(product_list.index(item),item) for index,item in enumerate(product_list): #enumerate打出列表的下標 print(index,item) user_choice = input("選擇買>>>") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >= 0: p_item = product_list[user_choice] if p_item[1] <= salary: shopping_list.append(p_item) salary -= p_item[1] print("Added %s into shopping cart,your current balanec is \033[31;1m%s\033[0m" %(p_item,salary)) else: print("you balance is too small ") elif user_choice == ‘q‘: print("---shopping list---") for p in shopping_list: print(p) print("your crrent balance:",salary) exit() else: print("invalid option")
字符串操作
>>> name = "my name is python" >>> name.capitalize() #首字母大寫 ‘My name is python‘ >>> name.count("a") #計數 1 >>> name.center(50,"-") #50個字符,不夠的用-補足 ‘----------------my name is python-----------------‘ >>> name.endswith("on") #判斷以什麽結尾 True >>> name.expandtabs(tabsize=30) #tab鍵長度 ‘my name is python‘ >>> name.find("name") #查找 從哪個開頭 3 >>> name[name.find("name")] #字符串切片 ‘n‘ >>> name.index("a") 4 >>> print(‘ab123‘.isalnum()) #是不是一個阿拉伯數字 True >>> "my name is {name}".format(name="test") #格式化輸出 ‘my name is test‘ >>> "my name is {name}".format_map({‘name‘:‘test‘}) #格式化輸出 ‘my name is test‘ >>> print(‘abC‘.isalpha()) #純英文字符 True >>> print(‘1A‘.isdecimal()) #是否十六進制 False >>> print(‘123‘.isdigit()) #是否一個整數 True >>> print(‘name‘.isidentifier()) #判斷是不是一個合法的標識符 True >>> print(‘a‘.islower()) #是否小寫 True >>> print(‘22‘.isnumeric()) #是不是一個數字 True >>> print(‘My Name Is ‘.istitle()) #首字母大寫 True >>> print(‘My Name Is‘.isprintable()) #是否可以打印 tty file drive file不能打印 True >>> print(‘A‘.isupper()) #是否大寫 True >>> print(‘‘.join([‘1‘,‘2‘,‘3‘])) #列表轉換為字符串 123 >>> print(‘+‘.join([‘1‘,‘2‘,‘3‘])) #列表轉換為字符串 1+2+3 >>> name.ljust(50,"*") #長度50 不夠的右邊補* ‘my name is python*********************************‘ >>> name.rjust(50,"*") #長度50 不夠的左邊補* ‘*********************************my name is python‘ >>> print(‘Abc‘.lower()) #變成小寫 abc >>> print(‘Abc‘.upper()) #變成大寫 ABC >>> print(‘ Abc \n ‘.lstrip()) #去除左邊的空格和回車 Abc >>> print(‘ Abc \n ‘.rstrip()) #去除右邊的空格和回車 Abc >>> print(‘ Abc \n ‘.strip()) #去除兩邊的空格和回車 Abc >>> print("python".translate(str.maketrans("abpth",‘12345‘))) #一一對應替換 3y45on >>> print("python python".replace("p","P",1)) #替換 最後一個參數為替換數量 Python python >>> print("python python".rfind("y")) #找到最右邊值的下標 8 >>> print("py th on".split()) #按照空格分成列表 [‘py‘, ‘th‘, ‘on‘] >>> print("py th on".split("t")) #按照傳參分成列表 [‘py ‘, ‘h on‘] >>> print(‘1+2\n+3+4‘.splitlines()) #按換行分成列表 [‘1+2‘, ‘+3+4‘] >>> print("python python".swapcase()) #全部轉換為大寫 PYTHON PYTHON >>> print("python python".title()) #轉換為標題 Python Python >>> print("python".zfill(50)) #補位 00000000000000000000000000000000000000000000python
字典操作
字典是一種key - value的數據類型。
>>> #語法 ... #字典是無序的 (沒有下標) ... info = { ... ‘stu01‘:‘A‘, ... ‘stu02‘:‘B‘, ... ‘stu03‘:‘C‘ ... } >>> #通過key取值 查詢 ... info[‘stu01‘] ‘A‘ >>> info[‘stu04‘] #需要確定有這個值用這種方法,沒有會報錯 Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: ‘stu04‘ >>> info.get(‘stu04‘) #沒有值時用get 不報錯 >>> #修改 ... info[‘stu01‘] = ‘D‘ #裏面有數值直接修改 >>> info[‘stu04‘] = ‘E‘ #裏面沒有直接添加 >>> info {‘stu04‘: ‘E‘, ‘stu01‘: ‘D‘, ‘stu02‘: ‘B‘, ‘stu03‘: ‘C‘} >>> #del 刪除 ... del info["stu04"] #刪除key為stu04的數據 >>> info {‘stu01‘: ‘D‘, ‘stu02‘: ‘B‘, ‘stu03‘: ‘C‘} >>> info.pop("stu01") #刪除stu01 ‘D‘ >>> info {‘stu02‘: ‘B‘, ‘stu03‘: ‘C‘} >>> info.popitem() #隨機刪除 (‘stu02‘, ‘B‘) >>> info {‘stu03‘: ‘C‘} >>> del info #刪除字典 >>> info Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘info‘ is not defined >>> #字典操作 ... info1 = { ... ‘stu01‘:‘A‘, ... ‘stu02‘:‘B‘, ... ‘stu03‘:‘C‘ ... } >>> >>> info2 = { ... ‘stu01‘:‘a‘, ... ‘stu04‘:‘D‘ ... } >>> >>> info1.update(info2) #合並修改 >>> info1 {‘stu04‘: ‘D‘, ‘stu01‘: ‘a‘, ‘stu02‘: ‘B‘, ‘stu03‘: ‘C‘} >>> info1.items() #把一個字典轉換為列表 dict_items([(‘stu04‘, ‘D‘), (‘stu01‘, ‘a‘), (‘stu02‘, ‘B‘), (‘stu03‘, ‘C‘)]) >>> info3 = dict.fromkeys([1,2,3],"test") #初始化一個字典 三個key共享一個內存地址 >>> info3 {1: ‘test‘, 2: ‘test‘, 3: ‘test‘} >>> >>> #多級字典嵌套及操作 ... menu = { ... "北京":{ ... "海澱":‘五道口‘, ... "昌平":‘沙河‘ ... }, ... "上海":{ ... "閔行":‘人民廣場‘ ... } ... } >>> menu.setdefault("深圳",{"羅湖":"東門"}) #沒有增加新的數據 {‘羅湖‘: ‘東門‘} >>> menu {‘北京‘: {‘海澱‘: ‘五道口‘, ‘昌平‘: ‘沙河‘}, ‘上海‘: {‘閔行‘: ‘人民廣場‘}, ‘深圳‘: {‘羅湖‘: ‘東門‘}} >>> >>> #字典的循環 ... for i in info1: ... print(i,info1[i]) ... stu04 D stu01 a stu02 B stu03 C >>> #把字典轉換為列表 效率不高 ... for k,v in info1.items(): ... print(k,v) ... stu04 D stu01 a stu02 B stu03 C
python之旅--數據類型