python基础知识3——基本的数据类型2——列表,元组,字典,集合
磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把——整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的。
一、列表
列表是可修改可变的,有序的,可迭代的,有索引和切片,可以是任意数据类型,可以包含任意多数据
1.列表的全部方法
如:['1','2']、['wupeiqi', 'alex']
1 >>> dir(list) 2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
每个列表都具备如下功能:
1 class list(object): 2 """ 3 list() -> new empty list 4 list(iterable) -> new list initialized from iterable's items 5 """在数组的末尾新增一项 6 def append(self, p_object): # real signature unknown; restored from __doc__ 7 """ 8 L.append(object) -- append object to end """ 9 pass 10 11 def count(self, value): # real signature unknown; restored from __doc__ 12 """ 查看lst中某一项出现的次数 13 L.count(value) -> integer -- return number of occurrences of value """ 14 return 0 15 16 def extend(self, iterable): # real signature unknown; restored from __doc__ 17 """将原列表与其他列表扩展成新列表 18 L.extend(iterable) -- extend list by appending elements from the iterable """ 19 pass 20 21 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 22 """返回列表中第一个匹配项的下标,找不到会报错 23 L.index(value, [start, [stop]]) -> integer -- return first index of value. 24 Raises ValueError if the value is not present. 25 """ 26 return 0 27 28 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 29 """在指定位置插入项 30 L.insert(index, object) -- insert object before index """ 31 pass 32 33 def pop(self, index=None): # real signature unknown; restored from __doc__ 34 """返回指定位置的值,并将其从列表中删除。默认对末尾项操作 35 L.pop([index]) -> item -- remove and return item at index (default last). 36 Raises IndexError if list is empty or index is out of range. 37 """ 38 pass 39 40 def remove(self, value): # real signature unknown; restored from __doc__ 41 """从列表中移除第一个符合与指定值相等的项 42 L.remove(value) -- remove first occurrence of value. 43 Raises ValueError if the value is not present. 44 """ 45 pass 46 47 def reverse(self): # real signature unknown; restored from __doc__ 48 """列表反转 49 L.reverse() -- reverse *IN PLACE* """ 50 pass 51 52 def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ 53 """排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。 54 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 55 cmp(x, y) -> -1, 0, 1 56 """ 57 pass 58 59 def __add__(self, y): # real signature unknown; restored from __doc__ 60 """ 字符串拼接 61 x.__add__(y) <==> x+y """ 62 pass 63 64 def __contains__(self, y): # real signature unknown; restored from __doc__ 65 """ 判断列表中是否包含某一项 66 x.__contains__(y) <==> y in x """ 67 pass 68 69 def __delitem__(self, y): # real signature unknown; restored from __doc__ 70 """删除列表中指定下标的项 71 x.__delitem__(y) <==> del x[y] """ 72 pass 73 74 def __delslice__(self, i, j): # real signature unknown; restored from __doc__ 75 """删除指定下标之间的内容,向下包含 76 x.__delslice__(i, j) <==> del x[i:j] 77 78 Use of negative indices is not supported. 79 """ 80 pass 81 82 def __eq__(self, y): # real signature unknown; restored from __doc__ 83 """ 判断两个列表是否相等 84 x.__eq__(y) <==> x==y """ 85 pass 86 87 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 88 """ 无条件被调用,通过实例访问属性。 89 x.__getattribute__('name') <==> x.name """ 90 pass 91 92 def __getitem__(self, y): # real signature unknown; restored from __doc__ 93 """ x.__getitem__(y) <==> x[y] """ 94 pass 95 96 def __getslice__(self, i, j): # real signature unknown; restored from __doc__ 97 """ 98 x.__getslice__(i, j) <==> x[i:j] 99 100 Use of negative indices is not supported. 101 """ 102 pass 103 104 def __ge__(self, y): # real signature unknown; restored from __doc__ 105 """ x.__ge__(y) <==> x>=y """ 106 pass 107 108 def __gt__(self, y): # real signature unknown; restored from __doc__ 109 """ x.__gt__(y) <==> x>y """ 110 pass 111 112 def __iadd__(self, y): # real signature unknown; restored from __doc__ 113 """ x.__iadd__(y) <==> x+=y """ 114 pass 115 116 def __imul__(self, y): # real signature unknown; restored from __doc__ 117 """ 118 x.__imul__(y) <==> x*=y """ 119 pass 120 121 def __init__(self, seq=()): # known special case of list.__init__ 122 """ 123 list() -> new empty list 124 list(iterable) -> new list initialized from iterable's items 125 # (copied from class doc) 126 """ 127 pass 128 129 def __iter__(self): # real signature unknown; restored from __doc__ 130 """ x.__iter__() <==> iter(x) """ 131 pass 132 133 def __len__(self): # real signature unknown; restored from __doc__ 134 """ x.__len__() <==> len(x) """ 135 pass 136 137 def __le__(self, y): # real signature unknown; restored from __doc__ 138 """ x.__le__(y) <==> x<=y """ 139 pass 140 141 def __lt__(self, y): # real signature unknown; restored from __doc__ 142 """ x.__lt__(y) <==> x<y """ 143 pass 144 145 def __mul__(self, n): # real signature unknown; restored from __doc__ 146 """ x.__mul__(n) <==> x*n """ 147 pass 148 149 @staticmethod # known case of __new__ 150 def __new__(S, *more): # real signature unknown; restored from __doc__ 151 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 152 pass 153 154 def __ne__(self, y): # real signature unknown; restored from __doc__ 155 """ x.__ne__(y) <==> x!=y """ 156 pass 157 158 def __repr__(self): # real signature unknown; restored from __doc__ 159 """ x.__repr__() <==> repr(x) """ 160 pass 161 162 def __reversed__(self): # real signature unknown; restored from __doc__ 163 """ L.__reversed__() -- return a reverse iterator over the list """ 164 pass 165 166 def __rmul__(self, n): # real signature unknown; restored from __doc__ 167 """ x.__rmul__(n) <==> n*x """ 168 pass 169 170 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 171 """ x.__setitem__(i, y) <==> x[i]=y """ 172 pass 173 174 def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ 175 """ 176 x.__setslice__(i, j, y) <==> x[i:j]=y 177 178 Use of negative indices is not supported. 179 """ 180 pass 181 182 def __sizeof__(self): # real signature unknown; restored from __doc__ 183 """ L.__sizeof__() -- size of L in memory, in bytes """ 184 pass 185 186 __hash__ = None 187 188 list 189 190 list Code
2.列表的常用方法
(1)append:向列表中添加项
insert:在列表的指定位置加入值
extend:列表的扩展;那么列表可以自己扩展自己么???当然是可以的啦!
1 >>> 2 >>> a = [1,2,3,4] 3 >>> a.append(5) 4 >>> a 5 [1, 2, 3, 4, 5] 6 >>> b = [6,7] 7 >>> a.extend(b) 8 >>> a 9 [1, 2, 3, 4, 5, 6, 7] 10 >>> a.insert(2,0) 11 >>> a 12 [1, 2, 0, 3, 4, 5, 6, 7]
1 >>> a 2 [1, 2, 3, 'a', 'b', 'c'] 3 >>> b 4 ['q', 'python'] 5 >>> a[len(a):]=b 6 >>> a 7 [1, 2, 3, 'a', 'b', 'c', 'q', 'python']
list.extend(L) 等效于 list[len(list):] = L,L是待并入的list
(2)index:返回列表中第一个匹配项的下标
__contain__:查看列表中是否包含某一项
count:查看列表中某一项出现的次数
1 >>> a 2 [1, 2, 0, 3, 4, 5, 6, 7] 3 >>> a.index(0) 4 2 5 >>> a.__contains__(7) 6 True 7 >>> a.__contains__(8) 8 False 9 >>> a.count(5) 10 1
(3)pop:删除并返回指定下标的值,默认为列表的最后一个值
remove:删除列表中与指定值匹配的第一个值
__delitem__:删除指定下标的值
__delslice__:删除指定下标区域内的所有值,下标向下包含
1 >>> a 2 [1, 2, 0, 3, 4, 5, 6, 7] 3 >>> a.pop() 4 7 5 >>> a 6 [1, 2, 0, 3, 4, 5, 6] 7 >>> a.pop(2) 8 0 9 >>> a 10 [1, 2, 3, 4, 5, 6] 11 >>> a.remove(2) 12 >>> a 13 [1, 3, 4, 5, 6] 14 >>> a.__delitem__(0) 15 >>> a 16 [3, 4, 5, 6] 17 >>> a.__delslice__(0,2) 18 >>> a 19 [5, 6]
(4)reverse:列表反转,这个反转并没有什么编码顺序,就是单纯的把原来的列表从头到尾调转过来而已。。。
sort:排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。
1 >>> a = [5,4,6,8,2,6,9] 2 >>> a.sort() 3 >>> a 4 [2, 4, 5, 6, 6, 8, 9] 5 >>> a.reverse() 6 >>> a 7 [9, 8, 6, 6, 5, 4, 2]
1 >>> a=[3,2,4,2,5,85,3,1] 2 >>> a.sort(reverse=True) 3 >>> a 4 [85, 5, 4, 3, 3, 2, 2, 1] 5 6 >>> a=[3,2,4,2,5,85,3,1] 7 >>> sorted(a, reverse=True) 8 [85, 5, 4, 3, 3, 2, 2, 1]
3. “+”:字符串和列表连接
1 >>> a=[1,2,3,4] 2 >>> s=[1,2] 3 >>> a+s 4 [1, 2, 3, 4, 1, 2] 5 >>> 6 >>> a-s 7 Traceback (most recent call last): 8 File "<stdin>", line 1, in <module> 9 TypeError: unsupported operand type(s) for -: 'list' and 'list' 10 >>> 11 >>> a='asd' 12 >>> s='as' 13 >>> a+s 14 'asdas' 15 >>> a-s 16 Traceback (most recent call last): 17 File "<stdin>", line 1, in <module> 18 TypeError: unsupported operand type(s) for -: 'str' and 'str' 19 >>>
生成列表:Python的简洁
1 >>> l = [x**2 for x in range(1,10)] 2 >>> l 3 [1, 4, 9, 16, 25, 36, 49, 64, 81]
1 >>> mybag = [' glass',' apple','green leaf '] #有的前面有空格,有的后面有空格 2 >>> [one.strip() for one in mybag] #去掉元素前后的空格 3 ['glass', 'apple', 'green leaf'] 4 enumerate
这是一个有意思的内置函数,本来我们可以通过for i in range(len(list))的方式得到一个list的每个元素编号,然后在用list[i]的方式得到该元素。如果要同时得到元素编号和元素怎么办?就是这样了:
1 >>> for i in range(len(week)): 2 ... print week[i]+' is '+str(i) #注意,i是int类型,如果和前面的用+连接,必须是str类型 3 ... 4 monday is 0 5 sunday is 1 6 friday is 2
python中提供了一个内置函数enumerate,能够实现类似的功能:
1 >>> for (i,day) in enumerate(week): 2 ... print day+' is '+str(i) 3 ... 4 monday is 0 5 sunday is 1 6 friday is 2
还有这个有趣的内置函数的例子:
1 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 2 >>> list(enumerate(seasons)) 3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 4 >>> list(enumerate(seasons, start=1)) 5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
3.列表的索引和切片
1 >>> list(range(10)) 2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 >>> l=list(range(10)) 4 >>> l 5 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 6 >>> l[:3] 7 [0, 1, 2] 8 >>> l[3:5] 9 [3, 4] 10 >>> l[-5:-3] 11 [5, 6] 12 >>> l[-5:] 13 [5, 6, 7, 8, 9] 14 >>> l[::2] 15 [0, 2, 4, 6, 8] 16 >>> (0,1,2,3,4,5,6)[:3] #元组也是列表只是不能改,所以也可以切片,得到的还是元组 17 (0, 1, 2) 18 >>> 'zhenghaolovexiaokai'[::2] #字符串可以看成列表 19 'zegalvxaki'
列表和字符串 两种类型的数据,有共同的地方,它们都属于序列(都是一些对象按照某个次序排列起来,这就是序列的最大特征),因此,就有很多类似的地方。如刚才演示的索引和切片,是非常一致的。
1 >>> l=[1,2,3,4,5] 2 >>> l[1] 3 2 4 >>> l.index(2) 5 1 6 >>> l[1]=1 #直接赋值修改,给覆盖了 7 >>> l 8 [1, 1, 3, 4, 5] 9 >>> s='asdfg' #字符串不可修改 10 >>> s[0]='b' 11 Traceback (most recent call last): 12 File "<stdin>", line 1, in <module> 13 TypeError: 'str' object does not support item assignment 14 >>>
4.通过extend()方法学习什么是可迭代的?
1 help(list.extend) #extend的参数必须是可迭代的。 2 3 extend(...) L.extend(iterable) -- extend list by appending elements from the iterable
1 >>> l=[1,2,3] 2 >>> s='python' 3 >>> lst=[7,8,9] 4 >>> lst.extend(l) #列表是可迭代的 5 >>> lst 6 [7, 8, 9, 1, 2, 3] 7 >>> lst.extend(s) 为啥? 8 >>> lst 9 [7, 8, 9, 1, 2, 3, 'p', 'y', 't', 'h', 'o', 'n']
>>> i=8 #整型不是可迭代的
>>> lst.extend(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
这就报错了。错误提示中告诉我们,那个数字 8,是 int 类型的对象,不是 iterable 的
这里用内建函数 hasattr()
判断一个字符串和列表是否是可迭代的?——得出字符串不是可迭代的,而列表是可迭代的(这里不太懂,为啥字符串不是可迭代的呢,和上面矛盾啊)
1 >>> str='python' 2 >>> hasattr(str,'__iter__') 3 False 4 >>> lst=[1,2] 5 >>> hasattr(lst,'__iter__') 6 True
hasattr()
的判断本质就是看那个类型中是否有__iter__
函数。还可以用 dir()
找一找,在数字、字符串、列表中,谁有__iter__
。同样还可找一找 元组,字典两种类型对象是否含有这个方法。
5.列表重要特征:
列表是可以修改的。这种修改,不是复制一个新的,而是在原地进行修改。
没有返回值,即不能赋值给某个变量。
1 >>> lst=[7,8,9] 2 >>> id(lst) 3 139795244578144 4 >>> lst.append(5) 5 >>> lst 6 [7, 8, 9, 5] 7 >>> id(lst) 8 139795244578144
1 >>> a=[1,2,3] 2 >>> b=a.extend([4,5,6]) #a原地修改了,没有返回值 3 >>> b #所以b什么也没有得到 4 >>> a 5 [1, 2, 3, 4, 5, 6]
6.列表生成式
1 >>> [x*x for x in range(1, 11) if x%2==0] 2 [4, 16, 36, 64, 100] 3 >>> [m+n for m in 'abc' for n in 'asd'] #两层循环 4 ['aa', 'as', 'ad', 'ba', 'bs', 'bd', 'ca', 'cs', 'cd']
7.字符串和列表比较
都属于序列类型的数据,很多方法很类似总结
list 和 str 的最大区别是:list 是可以改变的,str 不可变
二、元组
元组是不可修改不可变的,有序的,可迭代的,有索引和切片
1.元组的全部方法
如:(11,22,33)、('zhenghao', 'xiaokai')
1 1 >>> dir(tuple) 2 2 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
1 Help on class tuple in module __builtin__: 2 3 class tuple(object) 4 | tuple() -> empty tuple 5 | tuple(iterable) -> tuple initialized from iterable's items 6 | 7 | If the argument is a tuple, the return value is the same object. 8 | 9 | Methods defined here: 10 | 11 | __add__(...) 12 | x.__add__(y) <==> x+y 13 | 14 | __contains__(...) 15 | x.__contains__(y) <==> y in x 16 | 17 | __eq__(...) 18 | x.__eq__(y) <==> x==y 19 | 20 | __ge__(...) 21 | x.__ge__(y) <==> x>=y 22 | 23 | __getattribute__(...) 24 | x.__getattribute__('name') <==> x.name 25 | 26 | __getitem__(...) 27 | x.__getitem__(y) <==> x[y] 28 | 29 | __getnewargs__(...) 30 | 31 | __getslice__(...) 32 | x.__getslice__(i, j) <==> x[i:j] 33 | 34 | Use of negative indices is not supported. 35 | 36 | __gt__(...) 37 | x.__gt__(y) <==> x>y 38 | 39 | __hash__(...) 40 | x.__hash__() <==> hash(x) 41 | 42 | __iter__(...) 43 | x.__iter__() <==> iter(x) 44 | 45 | __le__(...) 46 | x.__le__(y) <==> x<=y 47 | 48 | __len__(...) 49 | x.__len__() <==> len(x) 50 | 51 | __lt__(...) 52 | x.__lt__(y) <==> x<y 53 | 54 | __mul__(...) 55 | x.__mul__(n) <==> x*n 56 | 57 | __ne__(...) 58 | x.__ne__(y) <==> x!=y 59 | 60 | __repr__(...) 61 | x.__repr__() <==> repr(x) 62 | 63 | __rmul__(...) 64 | x.__rmul__(n) <==> n*x 65 | 66 | count(...) 67 | T.count(value) -> integer -- return number of occurrences of value 68 | 69 | index(...) 70 | T.index(value, [start, [stop]]) -> integer -- return first index of value. 71 | Raises ValueError if the value is not present. 72 | 73 | ---------------------------------------------------------------------- 74 | Data and other attributes defined here: 75 | 76 | __new__ = <built-in method __new__ of type object> 77 | T.__new__(S, ...) -> a new object with type S, a subtype of T 78 79 None