首页 > 代码库 > python基础知识——基本的数据类型2——列表,元组,字典,集合
python基础知识——基本的数据类型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]
(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]
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
2.元组和字符串,列表的比较
tuple 是一种序列类型的数据,这点上跟 list/str 类似。它的特点就是其中的元素不能更改,所以也就没有添加,删除,修改等方法,这点上跟列表不同,倒是跟字符串类似;它的元素又可以是任何类型的数据,这点上跟 list 相同,但不同于 str。
1 >>> tup=(1, ‘python‘, [3,4], (5,6)) #元组的元素可以任意类型,和列表类似 2 >>> tup[1] #元组的索引,是序列类型 3 ‘python‘ 4 >>> tup[1]=2 #元组元素不可原地修改,和字符串类似 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 TypeError: ‘tuple‘ object does not support item assignment 8 >>> tup.append(2) #元素不可更改,没有此方法,和str类似 9 Traceback (most recent call last): 10 File "<stdin>", line 1, in <module> 11 AttributeError: ‘tuple‘ object has no attribute ‘append‘
>>> tup[2][0]
3
>>> tup[2].append(5) #元组的元素之一为列表,所以通过修改列表,元组样子改变了,但是注意元组的元素还不没变
>>> tup
(1, ‘python‘, [3, 4, 5], (5, 6))
3.元组的索引和切片
4.tuple 用在哪里?
既然它是 list 和 str 的杂合,它有什么用途呢?不是用 list 和 str 都可以了吗?
在很多时候,的确是用 list 和 str 都可以了。但是,看官不要忘记,我们用计算机语言解决的问题不都是简单问题,就如同我们的自然语言一样,虽然有的词汇看似可有可无,用别的也能替换之,但是我们依然需要在某些情况下使用它们.
一般认为,tuple 有这类特点,并且也是它使用的情景:
- Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
- 如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换 (需要使用一个特殊的函数)。
- Tuples 可以在 dictionary(字典,后面要讲述) 中被用做 key,但是 list 不行。Dictionary key 必须是不可变的。Tuple 本身是不可改变的,但是如果您有一个 list 的 tuple,那就认为是可变的了,用做 dictionary key 就是不安全的。只有字符串、整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key。
- Tuples 可以用在字符串格式化中。
三、字典
1.字典的全部方法
如:{‘name‘: ‘zhenghao‘, ‘age‘: 18} 、{‘host‘: ‘127.0.0.1‘, ‘port‘: 8000]}
1 >>> dir(dict) 2 [‘__class__‘, ‘__cmp__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘has_key‘, ‘items‘, ‘iteritems‘, ‘iterkeys‘, ‘itervalues‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘, ‘viewitems‘, ‘viewkeys‘, ‘viewvalues‘]
2.字典的常用方法
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object‘s 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除内容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 浅拷贝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根据key获取值,d是默认值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有项的列表形式 """ 44 """ D.items() -> list of D‘s (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 项可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D‘s keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 获取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 获取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {‘name‘:‘alex‘, ‘age‘: 18000} 91 [(‘name‘,‘sbsbsb‘),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D‘s values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有项,只是将内容保存至view对象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D‘s items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D‘s keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D‘s values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__(‘name‘) <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object‘s 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict code
字典是python数据类型中的一大亮点,在其中占有着独特的地位,在这里先介绍一下字典的特性,和list不同,字典是无序的,没有索引和切片,它依靠key和value之间的联系进行索引,由于这种特殊的索引方式,字典中不可以有重复的key。
(1)keys/values/items:取所有字典的key/取所有字典的value/取所有字典的key,value
1 >>> dic={‘name‘:‘zhenghao‘, ‘age‘:20} 2 >>> dic.keys() 3 [‘age‘, ‘name‘] 4 >>> dic.values() 5 [20, ‘zhenghao‘] 6 >>> dic.items() 7 [(‘age‘, 20), (‘name‘, ‘zhenghao‘)]
(2)已知key的情况下,获取value的值时可以使用‘字典名[key值]’的方法,在循环遍历中,尽管字典提供了for k,v in dic.items()的方法,但是为了避免占用内存空间,我们还是遍历key,再利用key的值就可以获取到value啦!
get:字典名[key值]的方式有一点弊端,那就是当key值不存在的时候会报错,这个时候我们使用get方法,可以避免报错的情况
1 >>> dic={‘name‘:‘zhenghao‘, ‘age‘:20} 2 >>> for n in dic: #循环时默认循环的是keys 3 ... print ‘key:‘, n, ‘value:‘, dic[n] 4 ... 5 key: age value: 20 6 key: name value: zhenghao 7 >>> dic[‘name‘] 8 ‘zhenghao‘ 9 >>> dic[‘score‘] #会报错 10 Traceback (most recent call last): 11 File "<stdin>", line 1, in <module> 12 KeyError: ‘score‘ 13 >>> dic.get(‘name‘) 14 ‘zhenghao‘ 15 >>> dic.get(‘score‘) #不会报错 16 >>>
(3)clear:清空字典
1 >>> dic.get(‘score‘) 2 >>> dic={‘name‘:‘zhenghao‘, ‘age‘:20} 3 >>> dic.clear() 4 >>> dic 5 {} 6 >>>
(4)pop:根据指定的key删除一组数据
popitem:随机的删除一组数据。。。我觉得这就是python在逗我。。。
(5)setdefault:dic.setdefault[key1],key1存在,则返回value1,不存在,则自动创建value = http://www.mamicode.com/‘None‘
1 >>> dic={‘name‘:‘zhenghao‘} 2 >>> dic.setdefault(‘name‘) 3 ‘zhenghao‘ 4 >>> dic.setdefault(‘age‘) 5 >>> dic 6 {‘age‘: None, ‘name‘: ‘zhenghao‘} 7 >>>
(6)update:dict1.update(dict2),判断dict2中的每一个key在dict1中是否存在,存在:就将dict1中的value更新成dict2中的,不存在:将key和value都复制过去
1 >>> dic 2 {‘age‘: None, ‘name‘: ‘E‘} 3 >>> dic1 = dic 4 >>> 5 >>> dic1 6 {‘age‘: None, ‘name‘: ‘E‘} 7 >>> dic2 = {‘age‘: 18, ‘name‘: ‘E‘,‘gender‘:‘female‘} 8 >>> dic1.update(dic2) 9 >>> dic1 10 {‘name‘: ‘E‘, ‘gender‘: ‘female‘, ‘age‘: 18}
(7)fromkeys:可以通过list或元组创建一个字典,
dict.fromkeys([1,2,3],‘test‘),可以创建一个字典,但是如果a.fromkeys([1,2,3],[]},创建的字典的值都是一个空列表,那么其中一个列表的值发生了变化,所有的列表都会跟着发生变化,因为这个方法就是很傻很天真的把所有value的指针指向了同一个列表。所以感觉这个方法也是逗我玩儿的。。。
>>> a = dict.fromkeys([1,2,3],‘test‘) >>> a {1: ‘test‘, 2: ‘test‘, 3: ‘test‘} >>> a = dict.fromkeys([1,2,3],[]) >>> a[1].append(‘test‘) >>> a {1: [‘test‘], 2: [‘test‘], 3: [‘test‘]}
3.字典可以原地修改
1 >>> dic={} 2 >>> id(dic) 3 139795272803784 4 >>> dic[‘name‘]=‘zhenghao‘ #直接给键值 5 >>> dic 6 {‘name‘: ‘zhenghao‘} 7 >>> id(dic) 8 139795272803784 9 >>>
3.字典的几种创建方法
4.字典练习题
1 练习:元素分类 2 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于等于 66 的值保存至第二个key的值中。 3 即: {‘k1‘: 大于66 , ‘k2‘: 小于等于66}
回答:
a=[11,22,33,44,55,66,77,88,99,90] dict1={‘k1‘:[],‘k2‘:[]} for i in a: if i >66: dict1[‘k1‘].append(i) else: dict1[‘k2‘].append(i) print dict1 最好的是用下面的方法来动态的扩展字典: a=[11,22,33,44,55,66,77,88,99,90] dict1={} #动态的增加字典 for i in a: if i >66: if ‘k1‘ in dict1.keys(): dict1[‘k1‘].append(i) else: dict1[‘k1‘] = [i,] else: if ‘k2‘ in dict1.keys(): dict1[‘k2‘].append(i) else: dict1[‘k2‘] = [i,] print dict1
python基础知识——基本的数据类型2——列表,元组,字典,集合