Python历程【数据类型之列表、元组、字典】
一、数据类型之列表(list)
1)定义列表
name = [11, 22, 33]
或
name1 = name(['Robin','Eric','john'])
2)列表方法
* 获取列表方法
方法一(help获取)
>>> help(list) Help on class list in module builtins: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key].
以下省略... ...
方法二(dir获取)
>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__' , '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__' , '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__' , '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__s izeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'ex tend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
3)列表方法使用
- append(追加元素)
name = ['aa','bb','cc'] print("原来元素:",name) name.append('dd') print("追加后的元素:",name) 输出结果 原来元素: ['aa', 'bb', 'cc'] 追加后的元素: ['aa', 'bb', 'cc', 'dd'] #dd为追加后的元素
- clear(清空列表元素)
name = ['aa','bb','cc'] print("原来元素:",name) name.clear() print("清除后的元素:",name) 输出结果 原来元素: ['aa', 'bb', 'cc'] 清除后的元素: [] #清空列表后
- copy & deepcopy(深浅拷贝)
import copy #导入copy模块 a = [1, 2, 3, 4, ['a', 'b']] #原始列表,列表内嵌套列表 b = a #赋值,传对象的引用,把a的值赋值给b print("输出a的内存值:", id(a)) #查看a在内存中的值 print("输出b的内存值:", id(b)) #查看b在内存中的值 c = copy.copy(a) #浅拷贝 d = copy.deepcopy(a) #深拷贝 a.append(5) #对a列表中下标为5,增加元素 a[4].append('c') #对a中的列表['a', 'b']元素进行修改 print("原始值:" 'a = ', a) print("赋值后的值:" 'b = ', b) print("浅拷贝的值:" 'c = ', c) print("深拷贝的值:" 'd = ', d) print("元素增加后的值:" 'a = ', a)
输出结果
输出a的内存值: 11167432
输出b的内存值: 11167432
原始值:a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
赋值后的值:b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
浅拷贝的值:c = [1, 2, 3, 4, ['a', 'b', 'c']]
深拷贝的值:d = [1, 2, 3, 4, ['a', 'b']]
元素更新后的值:a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
- count(统计总数)
#统计整数 list = [1, 15, 10, 6, 2, 6, 3, 6, 9]; print("原来列表:",list) sum = list.count(6) #统计6在列表中出现的次数 print("统计重复元素数量:",sum) 输出结果 原来列表: [1, 15, 10, 6, 2, 6, 3, 6, 9] 统计重复元素数量: 3 #统计字符串 list = [1, 'Ok', 'eric', 6, 'John',6, 'eric', 6, 9]; print("原来列表:",list) sum = list.count('eric') #统计eric在列表中出现的次数,注意字符串用引号包括 print("统计重复元素数量:",sum) 输出结果 原来列表: [1, 'Ok', 'eric', 6, 'John', 6, 'eric', 6, 9] 统计重复元素数量: 2
- extend(扩展)
name1 = ['aa','bb','cc'] name2 = [11, 22, 33, 44] print("name1的元素为:",name1) print("name2的元素为:",name2) name1.extend(name2) print("name1扩展后的元素为:",name1) 输出结果 name1的元素为: ['aa', 'bb', 'cc'] name2的元素为: [11, 22, 33, 44] name1扩展后的元素为: ['aa', 'bb', 'cc', 11, 22, 33, 44] #扩展后的name1列表 PS:extend扩展即把两个列表组合的过程
- index(索引)
list = [1, 15, 10, 6, 2, 6, 3, 6, 9]; print("原来列表:",list) sum = list.index(10) #元素所在列表中的下标 print("元素在列表中的index:",sum) 输出结果 原来列表: [1, 15, 10, 6, 2, 6, 3, 6, 9] 元素在列表中的index: 2
PS:下标从0开始
- insert(插入)
list = [1, 'Ok', 'eric', 6, 'John',6, 'eric', 6, 9]; print("原来列表:",list) list.insert(2,"Robin.Chow") #在下标为2处插入元素Robin.Chow print("元素在列表中的index:",list) 输出结果 原来列表: [1, 'Ok', 'eric', 6, 'John', 6, 'eric', 6, 9] 插入元素后: [1, 'Ok', 'Robin.Chow', 'eric', 6, 'John', 6, 'eric', 6, 9]
- pop(移除指定下标元素或最后一个元素)
list = [1, 'Ok', 'A', 4, 'John', 6, 'eric', 8, 9]; print("原来列表:",list) list.pop(4) #移除下标为4的元素 print("元素移除后列表:",list) 输出结果 原来列表: [1, 'Ok', 'A', 4, 'John', 6, 'eric', 8, 9] 元素移除后列表: [1, 'Ok', 'A', 4, 6, 'eric', 8, 9]
- remove(移除指定元素)
list = [1, 'Ok', 'A', 4, 'John', 6, 'eric', 8, 9]; print("原来列表:",list) list.remove('eric') #移除元素为eric的字符串 print("元素移除后列表:",list) 输出结果 原来列表: [1, 'Ok', 'A', 4, 'John', 6, 'eric', 8, 9] 元素移除后列表: [1, 'Ok', 'A', 4, 'John', 6, 8, 9]
- reverse(反转)
list = ['a', 'o', 'q', 'h', 'k', 'z', 'b', 'm']; print("原来列表:",list) list.reverse() print("元素在列表中的index:",list) 输出结果 原来列表: ['a', 'o', 'q', 'h', 'k', 'z', 'b', 'm'] 元素在列表中的index: ['m', 'b', 'z', 'k', 'h', 'q', 'o', 'a']
- sort(排序)
#对纯数字进行排序 list = [1, 15, 10, 6, 2, 6, 3, 6, 9]; print("原来列表:",list) list.sort() #对列表进行排序 print("元素在列表中的index:",list) 输出结果 原来列表: [1, 15, 10, 6, 2, 6, 3, 6, 9] 排序后列表: [1, 2, 3, 6, 6, 6, 9, 10, 15] #对单个字符进行排序 list = ['a', 'o', 'q', 'h', 'k', 'z', 'b', 'm']; print("原来列表:",list) list.sort() print("元素在列表中的index:",list) 输出结果 原来列表: ['a', 'o', 'q', 'h', 'k', 'z', 'b', 'm'] 元素在列表中的index: ['a', 'b', 'h', 'k', 'm', 'o', 'q', 'z']
- 其它
### 修改元素 >>> name = ['Erck','Chow','Robin','Tom'] >>> print(name) ['Erck', 'Chow', 'Robin', 'Tom'] >>> name[3] = 'ZHOU' #修改小标为3的元素 >>> print(name) ['Erck', 'Chow', 'Robin', 'ZHOU'] #ZHOU为修改后的元素
4)切片用法
>>> name = [11, 22, 33,'aa','bb','cc',"Robin","Chow"] >>> name[6] #截取下标为6的元素 'Robin' >>> name[1:4] #截取下标1到4的元素 [22, 33, 'aa'] >>> name[4:] #截取下标从4到最后一位元素 ['bb', 'cc', 'Robin', 'Chow'] >>> name[:5] #截取下标从0开始到下标为5结束的元素 [11, 22, 33, 'aa', 'bb'] >>> name[-2] #截取倒数第二的元素 'Robin' >>> name[-6:] #截取最后6个元素 [33, 'aa', 'bb', 'cc', 'Robin', 'Chow'] >>> name[1:-3] #截取1到-3的元素,但不包含-3的元素 [22, 33, 'aa', 'bb'] >>> name[-3:1] #切记,不能这样使用 []
5)利用for循环对重复的列表元素进行删除
name = [11, 22, 33,'aa','bb','cc',"Robin","Chow",'cc','aa',11,'cc'] for i in range(name.count('cc')): name.remove('cc') print(name) 输出结果 [11, 22, 33, 'aa', 'bb', 'Robin', 'Chow', 'cc', 'aa', 11, 'cc'] [11, 22, 33, 'aa', 'bb', 'Robin', 'Chow', 'aa', 11, 'cc'] [11, 22, 33, 'aa', 'bb', 'Robin', 'Chow', 'aa', 11]
6)源码中列举的方法
class list(object): """ list() -> new empty list list(iterable) -> new list initialized(初始化) from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -> None -- append object to end """ #在列表后面追加对象 pass def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ #从L项目中移除对象 pass def copy(self): # real signature unknown; restored from __doc__ """ L.copy() -> list -- a shallow(浅) copy of L """ #浅拷贝,拷贝列表结构,不拷贝对象 return [] def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ #返回列对象素个数 return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -> None -- extend list by appending elements(元素) from the iterable """ pass #扩展列表,添加元素到iterable(迭代项内) def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. #返回索引值 Raises ValueError if the value is not present. #如果值不存在,报错ValueError """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ #在指定索引前插入对象 pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). #移除最后索引值对象 Raises IndexError if list is empty or index is out of range(范围). #列表为空或超过索引范围,返回IndexError """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -> None -- remove first occurrence of value. #移除指定值 Raises ValueError if the value is not present. #值不存在,报错ValueError """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ #对列表内的元素反向 pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ #排序 pass
二、元组(tuple)
1)定义元组
tup = ('aa','bb','cc')
或
tup1 = tup((11,22,33,'aa','bb'))
PS:元组一旦创建,不能对元素进行修改
2)方法
- count(统计)
tup = (11,22,33,11) sum = tup.count(11) print("统计重复元素个数为:",sum) 输出结果 统计重复元素个数为: 2
- index(索引)
tup = [1, 15, 10, 6,12, 6, 3, 6, 9]; print("原来列表:",tup) sum = tup.index(12) #元素所在元组中的下标 print("元素在元组中的index:",sum) 原来元组元素: [1, 15, 10, 6, 12, 6, 3, 6, 9] 元素在元组中的index: 4
3)源码中元组的方法
class tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized(初始化) from iterable's items #从iterable项目中初始化元组 If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ #返回元组值 return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. #返回第一个索引值 Raises ValueError if the value is not present. #如果值不存在返回ValueError """ return 0 def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ #返回本身+值 pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ #返回本身key pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ #相等 pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ #获取属性 pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ #返回本身列表 pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ #大于等于 pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ #大于 pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ #返回本身hash值 pass def __init__(self, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items #对元组进行初始化 If the argument is a tuple, the return value is the same object. # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ #返回本身乘以值 pass
4)列表与元组的转换
tup = (11,22,33) #定义元组 tup = tuple((11,22,33)) #通过元组元素定义元组 tup = tuple([11,22,33]) #通过列表元素定义元组 ll = [11,22,33] #定义列表 tup = tuple(ll) #把列表元素转换成元组 ll = list(tu) #把元组转换成列表
三、字典(disc)
1)定义字典
dic = {"name": "Robin.Chow", "sex": "男","age":26}
或
dic = dict({"name": "Robin.Chow", "sex": "男","age":26})
2)特性
- 无序
- key值必须唯一
3)方法
>>> dir(dict) ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__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 ', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
- 增加
>>> dic = {"name": "Robin.Chow", "sex": "男","age":26} >>> dic['job'] = "运维工程师" >>> dic {'age': 26, 'sex': '男', 'name': 'Robin.Chow', 'job': '运维工程师'}
- 修改
dic = {"name": "Robin.Chow", "sex": "男","age":26} >>> dic {'age': 26, 'sex': '男', 'name': 'Robin.Chow', 'job': '运维工程师'} >>> dic['age'] = 28 >>> dic {'age': 28, 'sex': '男', 'name': 'Robin.Chow', 'job': '运维工程师'}
- 标准删除(pop)
>>> dic {'age': 28, 'sex': '男', 'name': 'Robin.Chow', 'job': '运维工程师'} >>> dic.pop('sex') #删除性别 '男' >>> dic {'age': 28, 'name': 'Robin.Chow', 'job': '运维工程师'}
- 随机删除(popitme)
>>> dic {'age': 28, 'name': 'Robin.Chow', 'job': '运维工程师'} >>> dic.popitem() ('age', 28) >>> dic {'name': 'Robin.Chow', 'job': '运维工程师'} >>> dic.popitem() ('name', 'Robin.Chow') >>> dic {'job': '运维工程师'}
- 查找(get)
>>> dic = {"name": "Robin.Chow", "sex": "男","age":26} >>> "name" in dic #判断字典内是否包换"name"key True >>> dic.get("age") #获取键值age的value 26 >>> dic["age"] 26
4)键值循环
#方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v)
5)源码中字典的方法
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized(初始化) with the name=value pairs in the keyword(关键字) argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ D.clear() -> None. Remove all items from D. """ #从D项目中移除 pass def copy(self): # real signature unknown; restored from __doc__ """ D.copy() -> a shallow copy of D """ #浅拷贝,拷贝D的结构,不拷贝元素 D.deepcopy() #深拷贝,拷贝D的结果及元素 pass @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable(迭代器) and values equal(等于) to value. """ pass 示例: dic = dict(k1='v1',k2='v2') new_dict = dic.fromkeys(['k1','k2','k3'],'v1') print(new_dict) def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ #如果键值不存在,默认会设定为none pass 示例: dic = dict(k1='v1',k2='v2') print(dic.get('k1')) print(dic.get('k2')) print(dic.get('k3')) print(dic.get('k3','Robin')) #如果k3值为空,则设置为Robin def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass 示例 dic = {'k1':'v1','k2':'v2'} print(dic.keys()) #keys print(dic.values()) #值 print(dic.items()) #输出所有键值对 for k in dic.keys(): #循环输出keys print(k) for v in dic.values(): #循环输出values print(v) for k,v in dic.items(): #循环输出items print(k,v) def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ #移除键值 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ #如果键值不存在,默认设置为none pass def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. #更新D,从字典E/迭代器F中更新 If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass 示例 dic = {'k1':'v1','k2':'v2'} dic.update({'k3':123}) print(dic) def values(self): # real signature unknown; restored from __doc__ """ D.values() -> an object providing a view on D's values """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ True if D has a key k, else False. """ pass def __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ #创建新对象 pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ #不等于 pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None