python基础(一)
一、列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def read_list(): 2 # 创建列表list 3 list = ['physics', 'chemistry', 1997, 2000] 4 print(list) 5 6 # 访问列表中的值 7 print(list[1]) 8 9 # 删除列表元素 10 del list[1] 11 print(list) 12 13 # len() list长度 14 print(len(list)) 15 16 # + 连接 17 list1 = ['time', 'them', 'item'] 18 list += list1 19 print(list) 20 21 # * 重复 22 li = ['he!']*4 23 print(li) 24 25 x = [4,6,2,1,7,9] 26 x.sort(reverse=True) 27 print(x) # output:[9,7,6,4,2,1] 28 29 x = ['aardvark','abalone','acme','add','aerate'] 30 x.sort(key=len) 31 print(x) # output:['add','acme','aerate','abalone','aardvark'] 32 33 if __name__ == "__main__": 34 read_list() 35 36 37 # in 元素是否在列表中 38 # cmp(list1,list2) 比较两个列表的元素 39 # len() 列表元素的个数 40 # max() 列表中元素的最大值 41 # min() 列表中元素的最小值 42 # list(seq) 将元组转换为列表 43 # list.append() 在列表末尾添加新的对象 44 # list.count() 统计某个元素在列表中出现的次数 45 # list.extend(seq) 在列表末尾一次性追加另一个序列的多个元素 46 # list.index() 从列表中找出某个值第一个匹配项的索引位置 47 # list.pop() 移除列表中的一个元素 48 # list.remove() 移除列表中某个值的第一个匹配项 49 # list.reverse() 反向列表中元素 50 # list.sort() 将原列表进行排序
二、元组
元组:不可变序列
一旦定义就不能再修改,使用逗号分隔符进行分割,即使只有一个值,也必须加一个逗号:(42,)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def read_tuple(): 2 # 创建元组 3 tuple = ('physic', 'chemistry', 1997, 2000) 4 print(tuple[2]) 5 tuple1 = (1,2,3) 6 tuple += tuple1 7 print(tuple) 8 9 # del tuple1 10 # print tuple1 11 # print tuple[2] 12 13 # cmp(tuple1,tuple2) 比较两个元组元素 14 # len() 计算元组元素的个数 15 # max() 返回元组中元素的最大值 16 # min() 返回元组中元素的最小值 17 # tuple(seq) 将列表转换为元组 18 x = tuple([1,2,3]) 19 print(x) # output:(1,2,3) 20 21 x = tuple('abc') 22 print(x) # output:('a','b','c') 23 24 x = tuple((1,2,3)) 25 print(x) # output:(1,2,3) 26 27 print(cmp(tuple1, tuple)) # 元组一旦定义就不能再修改 28 if __name__ == "__main__": read_tuple()
三、字符串
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1、* 重复输出字符串 >>> print('hello'*10) hellohellohellohellohellohellohellohellohellohello 2、[], [:] 通过索引获取字符串中的字符,这里和列表中的切片方法一样 >>> print('hello word'[2:]) llo word 3、in 成员运算符,如果字符串中包含给定的字符,则返回True >>> print('ell' in 'hello word') True 4、% 格式化字符串 >>> print('alex is a good teacher') alex is a good teacher >>> print('%s is a good teacher'%'alex') alex is a good teacher 5、+ ,‘’.join 字符串拼接(两种方法) >>> a = 'abc' >>> b = '123' >>> c = a + b >>> print(c) abc123 >>> a = 'abc' >>> b = '123' >>> c = ''.join([a,b]) >>> print(c) abc123 --------------------字符串的内置方法-------------------- st = ‘hello kitty’ 1、count #统计字符串中的元素个数 >>> st = 'hello kitty' >>> print(st.count('l')) 2 2、capitalize #将整个字符串中的首个字母大写 >>> print(st.capitalize()) Hello kitty 3、center # 居中 >>> print(st.center(50,'-')) -------------------hello kitty-------------------- 4、endswith # 以某个内容结尾,返回布尔值 >>> print(st.endswith('y')) True 5、startswith # 以某个内容开头,返回布尔值 >>> print(st.startswith('h')) True 6、expandtabs(tabsize=20) >>> st = 'he\tllo kitty' >>> print(st.expandtabs(tabsize=20)) he llo kitty 7、find #查找第一个元素,并返回索引值 >>> st = 'hello kitty' >>> print(st.find('t')) 8 8、format format_map #格式化输出 >>> st = 'hello kitty {name} is {age}' >>> print(st.format(name = 'alex',age = 37)) hello kitty alex is 37 >>> st = 'hello kitty {name} is {age}' >>> print(st.format_map({'name':'alex','age':37})) hello kitty alex is 37 9、index #查找元素并返回索引值,元素不存在则会报错 >>> print(st.index('a')) 14 >>> print(st.index('w')) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> print(st.index('w')) ValueError: substring not found 10、 isalnum # 判断字符串中是否包含字母或数字,返回布尔值 >>>print('abc456'.isalnum()) True 11、isdigit isnumeric # 判断字符串是否是一个整型,返回布尔值 >>> print('123456'.isdigit()) True >>> print('123456'.isnumeric()) True 12、isidentifier # 判断是否是非法字符 >>> print('123456'.isidentifier()) False 13、islower # 判断所有字符串是否是小写 >>> print('asda'.islower()) True 14、isupper # 判断所有字符串是否是大写 >>> print('ASD'.isupper()) True 15、isspace # 判断字符串中是否是空格 >>> print(' '.isspace()) True 16、istitle # 判断是否是标题(标题的单词首字母是大写) >>> print('My Title'.istitle()) True 17、lower #所有大写变小写 >>> print('My Title'.lower()) my title 18、upper #所有小写变大写 >>> print('My Title'.upper()) MY TITLE 19、swapcase #字母大小写翻转 >>> print('My Title'.swapcase()) mY tITLE 20、ljust #左对齐 rjust #右对齐 >>> print('My Title'.ljust(50,'*')) My Title****************************************** >>> print('My Title'.rjust(50,'*')) ******************************************My Title 21、strip #去掉空格和换行符 print(' My Title\n') print('ok') My Title ok print(' My Title\n'.strip()) print('ok') My Title ok 22、replace #替换 >>> print('My title'.replace('t','lesson',2)) #参数2,表示替换几次 My lessonilessonle 23、split #分割 >>> print('My title'.split('i')) ['My t', 'tle'] 22、title # 以标题的形式输出 >>> print('My title title'.title()) My Title Title
四、字典
字典的两大特点:无序,键唯一
通过dict关键字创建字典
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 两种创建字典的方式: 2 >>> dic1 = dict((('name','szx'),('hoppy','123'))) 3 >>> print(dic1) 4 {'name': 'szx', 'hoppy': '123'} 5 6 7 >>> dic1 = {'name':'szx','hoppy':'123'} 8 >>> print(dic1) 9 {'name': 'szx', 'hoppy': '123'} 10 11 字典的操作 12 1、增 13 >>> dic1 = {'name': 'szx'} 14 >>> dic1['age'] = 18 15 >>> print(dic1) 16 {'name': 'szx', 'age': 18} 17 18 >>> dic1.setdefault('age',34) #键存在,不改动,返回字典中相应的键对应的值; 19 18 20 21 >>> dic1.setdefault('hoppy','girl') #键不存在,在字典里增加新的键值对,并返回相应的值; 22 'girl' 23 24 2、查 25 26 通过键去查找值 27 >>> dic3 = {'name': 'szx','age':'18'} 28 >>> print(dic3['name']) 29 szx 30 查看字典中的键、值、键值对的方法: 31 32 >>> dic3 = {'name': 'szx','age':'18'} #查看字典中的键 33 >>> print(dic3.keys()) 34 dict_keys(['name', 'age']) #取出的值不是列表 35 >>> print(list(dic3.keys())) #通过list 转换为列表 36 ['name', 'age'] 37 38 >>> print(dic3.values()) #查看字典中的所有值 39 dict_values(['szx', '18']) 40 41 >>> print(dic3.items()) #查看字典中的键值对 42 dict_items([('name', 'szx'), ('age', '18')]) 43 44 3、改 45 46 >>> dic1 = {'name': 'szx'} 47 >>> dic1['name'] = '123' #取出键 并重新赋值 48 >>> print(dic1) 49 {'name': '123'} 50 51 update 键存在则更新,键不存在则添加 52 53 >>> dic4 = {'name': 'szx','age':'18'} 54 >>> dic5 = {'1':'222','age':'555'} 55 >>> dic4.update(dic5) 56 >>> print(dic4) 57 {'name': 'szx', 'age': '555', '1': '222'} 58 >>> print(dic5) 59 {'1': '222', 'age': '555'} 60 61 4、删 62 63 del #删除字典中指定的键值对 64 65 >>> dic6 = {'name': 'szx','age':'18'} 66 >>> del dic6['name'] 67 >>> print(dic6) 68 {'age': '18'} 69 70 clear #清空字典 71 72 >>> dic6 = {'name': 'szx','age':'18'} 73 >>> dic6.clear() 74 >>> print(dic6) 75 {} 76 77 pop(删除指定的键值对,并返回该键值对的值) popitem(随机删除某组键值对,并返回值) 78 79 >>> dic6 = {'name': 'szx','age':'18'} 80 >>> reg = dic6.pop('name') 81 >>> print(reg) # 返回删除的值 82 szx 83 >>> print(dic6) 84 {'age': '18'} 85 86 del #删除整个字典 87 88 >>> dic6 = {'name': 'szx','age':'18'} 89 >>> del dic6 #从内存删除,打印会出错 90 >>> print(dic6) 91 Traceback (most recent call last): 92 File "<pyshell#36>", line 1, in <module> 93 print(dic6) 94 NameError: name 'dic6' is not defined 95 96 字典的其它操作: 97 1、fromkeys创建字典 98 99 >>> dic7 = dict.fromkeys(['host1','host2','host3'],'test') 100 >>> print(dic7) 101 {'host1': 'test', 'host2': 'test', 'host3': 'test'} 102 103 104 >>> dic7 = dict.fromkeys(['host1','host2','host3'],['test1','test2']) 105 >>> dic7['host2'][1] = 'test3' #不能单独修改 106 >>> print(dic7) 107 {'host1': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host3': ['test1', 'test3']} 108 109 2、字典排序 sorted 110 111 >>> dic = {5:'555',2:'666',4:'444'} 112 >>> print(sorted(dic)) #键排序 113 [2, 4, 5] 114 115 >>> dic = {5:'555',2:'666',4:'444'} 116 >>> print(sorted(dic.values())) #值排序 117 ['666', '444', '555'] 118 119 >>> dic = {5:'555',2:'666',4:'444'} 120 >>> print(sorted(dic.items())) #键值对排序 121 [(2, '666'), (4, '444'), (5, '555')] 122 123 3、字典的遍历 124 125 >>> dic1 = {'name':'szx','hoppy':17} 126 >>> for i in dic1: 127 print(i,dic1[i]) 128 name szx 129 hoppy 17 130 131 132 >>> dic1 = {'name':'szx','hoppy':17} 133 >>> for i,v in dic1.items(): 134 print(i,v) 135 name szx 136 hoppy 17
Python字典包含了以下内置函数:
序号 | 函数及描述 | 实例 |
---|---|---|
1 | len(dict) 计算字典元素个数,即键的总数。 |
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
|
2 | str(dict) 输出字典,以可打印的字符串表示。 |
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
|
3 | type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 |
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>
|
Python字典包含了以下内置方法:
序号 | 函数及描述 |
---|---|
1 | radiansdict.clear() 删除字典内所有元素 |
2 | radiansdict.copy() 返回一个字典的浅复制 |
3 | radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
4 | radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 |
5 | key in dict 如果键在字典dict里返回true,否则返回false |
6 | radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 |
7 | radiansdict.keys() 以列表返回一个字典所有的键 |
8 | radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default |
9 | radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
10 | radiansdict.values() 以列表返回字典中的所有值 |
11 | pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。 |
12 | popitem() 随机返回并删除字典中的一对键和值(一般删除末尾对)。 |
五、集合(set)的基本操作
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 集合中的元素必须是不可变类型
- 关系测试,测试两组数据之前的交集、差集、并集等关
常用操作
1 a = set([1,2,3,4,5]) 2 b = set([4,5,6,7,8]) 3 4 print(a.intersection(b)) #交集 {4, 5} 5 print(a&b) 6 7 print(a.union(b)) #并集 {1, 2, 3, 4, 5, 6, 7, 8} 8 print(a|b) 9 10 print(a.difference(b)) #插集、得到的是a里有的b里没有的 {1, 2, 3} 11 print(a-b) 12 13 print(b.difference(a)) #插集、得到的是b里有的a里没有的 {8, 6, 7} 14 print(b-a) 15 16 print(a.symmetric_difference(b)) #方向交集、{1, 2, 3, 6, 7, 8} 17 print(a^b) 18 19 20 21 1 s = set([3,5,9,10]) #创建一个数值集合 22 2 23 3 t = set("Hello") #创建一个唯一字符的集合 24 4 25 5 26 6 a = t | s # t 和 s的并集 27 7 28 8 b = t & s # t 和 s的交集 29 9 30 10 c = t – s # 求差集(项在t中,但不在s中) 31 11 32 12 d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 33 13 34 14 35 15 36 16 基本操作: 37 17 38 18 t.add('x') # 添加一项 39 19 40 20 s.update([10,37,42]) # 在s中添加多项 41 21 42 22 t.pop() #随机删除 t.disicard() 指定删除(元素不存在会报错) 43 23 44 24 使用remove()可以删除指定一项(元素不存在会报错): 45 25 46 26 t.remove('H') 47 27 48 28 49 29 len(s) 50 30 set 的长度 51 31 52 32 x in s 53 33 测试 x 是否是 s 的成员 54 34 55 35 x not in s 56 36 测试 x 是否不是 s 的成员 57 37 58 38 s.issubset(t) 59 39 s <= t 60 40 测试是否 s 中的每一个元素都在 t 中 61 41 62 42 s.issuperset(t) 63 43 s >= t 64 44 测试是否 t 中的每一个元素都在 s 中 65 45 66 46 s.union(t) 67 47 s | t 68 48 返回一个新的 set 包含 s 和 t 中的每一个元素 69 49 70 50 s.intersection(t) 71 51 s & t 72 52 返回一个新的 set 包含 s 和 t 中的公共元素 73 53 74 54 s.difference(t) 75 55 s - t 76 56 返回一个新的 set 包含 s 中有但是 t 中没有的元素 77 57 78 58 s.symmetric_difference(t) 79 59 s ^ t 80 60 返回一个新的 set 包含 s 和 t 中不重复的元素 81 61 82 62 s.copy(
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)