第二章 Python数据类型详解
基本概念
迭代(iteration):如果給定一個list或tuple,我們可以通過for循環(huán)來遍歷,這種遍歷我們稱為迭代(iteration)
可變:value改變,id不變,可變類型是不可hash類型
不可變:value改變,id就變,不可變類型是可hash類型
字符串
字符串是可迭代,不可變的
example_str='life is short you need python'
常用操作:index()、len()、切片、成員運(yùn)算、strip()、split()、join()、循環(huán)遍歷、replace()、count()、upper()、lower()、enumerate()、isdigit()
example_str='life|is|short you|need|python' example_bank=' today is Monday ' example_other='***good morning***' #index()/rindex():獲取索引值(適用于可遍歷對象如列表,字符串,元祖) print(example_str.index('p')) #len():求長度() print(len(example_str)) #[::]:切片 print(example_str[::]) #取所有字符串 print(example_str[0:10:])#從左向右切,(默認(rèn)步長為1) print(example_str[0:10:1])#從左向右切,步長為1 print(example_str[0:10:2])#從左向右切,步長為2 print(example_str[::-1])#從右向左切,步長為1 print(example_str[-1:-8:-2])#從右向左切,步長為2 #in/not in:成員運(yùn)算(適用于可迭代對象如列表,字符串,元祖) life in example_str live not in example_str #strip()/lstrip()/rstrip():移除空白 print(example_bank.strip())#strip()默認(rèn)移除字符串前后的空白 print(example_other.strip('*'))#移除字符串前后的* #split():切分 example_split=example_str.split('|')#按'|'對字符串進(jìn)行切分并存在列表里 print(example_split) #join():連接 example_join=('*').join(example_split)#按'*'將字符串連接在一起,可迭代對象必須都是字符串 print(example_join) #for str in example_str:循環(huán)遍歷(適用于可迭代對象如列表、字符串和元祖) for s in example_str:print(s) #replace():替換 print(example_str.replace('short','long'))#字符串替換,replace(para1,para2)中需指定兩個參數(shù) #count():計數(shù) print(example_str.count('s'))#統(tǒng)計字符串中's'出現(xiàn)的個數(shù) #upper:大寫 print(example_str.upper())#將字符串中所有字符都變成大寫 #lower:小寫 print(example_str.lower())#將字符串中所有字符都變成小寫 #enumerate():枚舉(適用于可迭代對象如列表、字符串和元祖) for index,s in enumerate(example_str): #同時獲取索引和值print(index,s) #isdigit(): 可以判斷bytes和unicode類型,檢測字符串是否只由數(shù)字組成 age=input('Please input your age:') print(type(age))了解:format()、startswith()、endswith()、find()、center()、expandtabs()、capitalize()
#format():格式化 print('{0}{1}{0}'.format('love','you')) print('{name}{age}{nature}'.format(nature='cute',name='luoli',age=18)) #startswith():判斷開頭 print(example_str.startswith('life')) #endswith():p判斷結(jié)尾 print(example_str.endswith('python')) #find()/rfind():查找字符串 print(example_str.find('s',0,6))#找不到則返回-1 print(example_str.index('s',0,6))#找不到會報錯 #center()/ljust()/rjust()/zfill():填充 name='luoli' print(name.center(20,'-') print(name.rjust(20,'*')) print(name.ljust(20,'+')) print(name.zfill(10)) #expandtabs(tabsize=8):指定轉(zhuǎn)換字符串中的 tab 符號('\t')轉(zhuǎn)為空格的字符數(shù) name='luoli\tcute' print(name.expandtabs(8)) #capitalize()/swapcase()/title():首字母大寫/大小寫翻轉(zhuǎn)/每個單詞的首字母大寫 name='hello,luoli' print(name.capitalize()) print(name.swapcase()) print(name.title()) View Code列表
列表是可迭代,可變的
? example_list=['Monday','Tuesday','Friday','Sunday']
常用操作:切片、長度、遍歷、查找元素、添加元素、刪除元素、排序
example_list=['Monday','Tuesday','Wednesday ','Thursday','Friday'] #[::]:切片 print(example_list[2:4]) #len():長度 print(len(example_list)) #遍歷 for i in example_list:print(i) #查找元素 print('Monday' in example_list) #in /not in print(example_list.index('Tuesday',0,4)) #index() print(example_list.count('Tuesday')) #count() #添加元素 example_append=['Saturday','Sunday'] #append() example_list.append(example_append) print(example_list) example_extend=['Saturday','Sunday'] #extend():可以將另一個集合中的元素逐一添加到列表中 example_list.extend(example_extend) print(example_list) example_list.insert(1,'hello') #insert():可以在指定位置添加元素 print(example_list) #刪除元素 del example_list[0] #del():根據(jù)下標(biāo)進(jìn)行刪除 print(example_list) example_list.pop() #pop():刪除最后一個元素 print(example_list) example_list.remove('Tuesday') #remove():根據(jù)元素的值進(jìn)行刪除 print(example_list) #排序 a=[1,4,3,2,5] #sort():按特定順序重新排列,默認(rèn)由小到大 a.sort() print(a) a.sort(reverse=True) #將list逆置 print(a)元祖
元祖是可迭代,不可變的
example_tuple=('apple','peach','cherry','orange')
元祖和列表非常相似,但是元祖不可變,一旦初始化就不能進(jìn)行修改
example_tuple=('apple','peach','cherry','pear','orange') #index()/count() print(example_tuple.index('apple')) print(example_tuple.count('peach')) #切片 print(example_tuple[0:4:2]) #長度 print(len(example_tuple)) #循環(huán) for i in example_tuple:print(i) #成員運(yùn)算 print('apple' in example_tuple)?字典
字典是可迭代,可變的
example_dict={'name':'luoli','age':18,'sex':'female'}
默認(rèn)情況下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同時迭代key 和value,可以用for k,v in d.items()
example_dic={'apple':18,'beach':20,'pear':30,'cherry':40,'orange':50} #按key取值,可存可取 print(example_dic['apple']) #遍歷 for i,s in example_dic.items():print(i,example_dic[i]) #成員運(yùn)算 print('apple' in example_dic) #添加元素 a={'x':2,'y':3} a['z']=5 #在使用dic['key']=value時,這個'key'在字典中,如果不存在就會新增這個元素,如果'key'存在,新value就會覆蓋原value for i,s in a.items():print(i,a[i]) a.setdefault('y',5) #key存在,則不賦值,key不存在,則在字典中新增key和value for i,s in a.items():print(i,a[i]) #刪除元素 b={'m':12,'n':18} del b['m'] #del()刪除指定的元素 for i in b:print(i) b.clear() #清空整個字典 print(b)集合
集合是可迭代,可變的
example_set={'a','b','c','d','e'}
集合的目的是將不同的值存放到一起,不同的集合間用來做關(guān)系運(yùn)算,主要用于去重和關(guān)系運(yùn)算
example_set1={'a','b','f'} example_set2={'a','b','c','d','e'} #長度 print(len(example_set1)) #成員運(yùn)算 print('a' in example_set1) print('d' not in example_set1) #合集 | print(example_set1|example_set2) #交集 & print(example_set1&example_set2) #差集 - print(example_set1-example_set2) #對稱差集 print(example_set1^example_set2) #== print(example_set1==example_set2) #父集 > >= print(example_set1>example_set2) #子集 < <= print(example_set1<example_set2)練習(xí)
(1).test_list=[1,2,3,4,5,6,7,5,3,6,67,43,12,0,34,23] a.去除列表中的重復(fù)元素 b.將去重后的列表進(jìn)行由小到大排序 test_list=[1,2,3,4,5,6,7,5,3,6,67,43,12,0,34,23] s=set(test_list) li=list(s) li.sort() print(li) View Code (2).部門員工管理a.能夠查詢部門是否有該員工
b.能夠增加員工名稱
c.能夠刪除員工名稱
d.能夠修改員工名稱 msg=''' 1. 添加名? 2. 刪除名? 3. 修改名? 4. 查詢名? 5. 退出系統(tǒng) ''' list=[] no_quit=True while no_quit:print(msg)#print(list)user_choice=input('Please chioce the number:')if user_choice.isdigit():choice=int(user_choice)if choice == 1:add_name=input('Pleaase enter the username:')list.append(add_name)elif choice == 2:move_name=input('Please enter the username:')if move_name in list:list.remove(move_name)else:print('The username is not exist!')elif choice == 3:old_name=input('Please enter the old name:')if old_name in list:i=list.index(old_name)new_name=input('Please input the new name:')list[i]=new_nameprint('change succeed!')elif choice == 4:query_name=input('Please enter the search name:')if query_name in list:print(list)else:print('Search failed!')elif choice == 5:no_quit=Falsecontinueelse:print('Error input! Please choose again')else:print('Illegal choice!') View Code
轉(zhuǎn)載于:https://www.cnblogs.com/iamluoli/p/8026912.html
總結(jié)
以上是生活随笔為你收集整理的第二章 Python数据类型详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 这个时代,给了我们年轻人太多
- 下一篇: iOS 采集音视频及写入文件