python全栈学习笔记(六)python入门--基本数据类型 list tupple dict
4、列表
创建列表:
In [29]: a = [1,2,3,4,5,6] In [30]: type(a) Out[30]: list
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 切片
- 循环
- 包含
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) -- append object to end """ pass 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) -- extend list by appending elements from the iterable """ pass 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. """ 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. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iadd__(self, y): # real signature unknown; restored from __doc__ """ x.__iadd__(y) <==> x+=y """ pass def __imul__(self, y): # real signature unknown; restored from __doc__ """ x.__imul__(y) <==> x*=y """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ """ x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None list
列表也是序列一种,可以进行索引切片
In [32]: a Out[32]: [1, 2, 3, 4, 5, 6] In [33]: a[2] Out[33]: 3 In [34]: a[0:4] Out[34]: [1, 2, 3, 4] In [35]: a[0:4:2] Out[35]: [1, 3]
因为拟态,列表也可以做加法和乘法运算:
>>> [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6] >>> [110]*10 [110, 110, 110, 110, 110, 110, 110, 110, 110, 110]
1)、list的追加方法append :
>>> a = [1,2,3,4] >>> a.append(5) >>> a [1, 2, 3, 4, 5]
2)、如果想批量添加的话使用 extend方法:
>>> a [1, 2, 3, 4, 5] >>> a.extend([6,7,8,9,10]) >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3)、index方法和字符串的index方法一样,可以找到元素的索引:
>>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> a.index(1) 0
4)、列表insert方法可指定位置插入成员 分别放两个参数
>>> name_list = ['root','tom','tim'] >>> name_list.insert(1,'laoni') >>> name_list ['root', 'laoni', 'tom', 'tim']
5)、pop方法是拿到列表的最后一个元素,同时原list里的最后一个元素被移除掉
>>> name_list ['root', 'laoni', 'tom', 'tim'] >>> name_list.pop() 'tim' >>> name_list ['root', 'laoni', 'tom']
6)、remove方法是移除指定的元素,如果有多个值相同的就移除最先找到的
>>> name_list ['root', 'laoni', 'tom', 'bob', 'bob'] >>> name_list.remove('bob') >>> name_list ['root', 'laoni', 'tom', 'bob']
7)、reverse方法是 把所有元素翻转过来
>>> name_list ['root', 'laoni', 'tom', 'bob'] >>> name_list.reverse() >>> name_list ['bob', 'tom', 'laoni', 'root']
8)、del方法删除指定索引的元素
>>> name_list ['bob', 'tom', 'laoni', 'root'] >>> del name_list[2] >>> name_list ['bob', 'tom', 'root']
基本数据类型---元组(tupple)
创建元祖:
>>> age_tupple = () >>> type(age_tupple) <type 'tuple'> >>> age_tupple = (12) >>> type(age_tupple) <type 'int'> >>> age_tupple = (12,) >>> type(age_tupple) <type 'tuple'>
注意:如果元组只有一个元素,需要在元素后面加上逗号,不然不是元组
- 索引
- 切片
- 循环
- 长度
- 包含
lass tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items 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. """ return 0 def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ 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): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ T.__sizeof__() -- size of T in memory, in bytes """ pass tuple
元组与列表一样,也是一种序列。唯一的不同是元组不能修改。(实际上字符串也是如此。)
创建元组的语法很简单:如果你用逗号分隔了一些值,那么你就自动创建了元组。

6、字典(无序)
字典可以通过下面的方式创建:
phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538}
注意:字典中的键是唯一的(其他类型的映射也是这样),而值并不是唯一的。
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
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. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] 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__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, 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 def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ 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): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None dict
1)、keys方法拿到字典所有的键,values方法拿到字典所有的值,items方法拿到所有的键值对
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} print(phonebook.keys()) print(phonebook.values()) print(phonebook.items())
执行结果:
dict_keys(['customer', 'Tim', 'Bob', 'Tom']) dict_values([12538, 120, 119, 110]) dict_items([('customer', 12538), ('Tim', 120), ('Bob', 119), ('Tom', 110)])
2)、clear方法,清除所有的键值对
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} phonebook.clear() print(phonebook)
执行结果:
{}
3)、get方法:根据key来获取值,如果key不存在,返回默认值
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} print(phonebook.get('Bob')) print(phonebook.get('BoB','不存在'))
执行结果:
119
不存在
4)、字典也可以通过索引的方式获取值,但如果获取不到则报错
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} print(phonebook['customer']) print(phonebook['Pitter'])
执行结果:
12538 Traceback (most recent call last): File "C:/c9.py", line 5, in <module> print(phonebook['Pitter']) KeyError: 'Pitter'
5)、del方法 删除指定索引的键值对
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} del phonebook['Tim'] print(phonebook)
执行结果:
{'customer': 12538, 'Bob': 119, 'Tom': 110}
6)、update方法,更新字典
#!/usr/bin/env python3 # -*- coding:utf-8 -*- phonebook = {'Tom':110,'Tim':120,'Bob':119,'customer':12538} phonebook_bak = {'Blue':911,'Kitty':123} phonebook.update(phonebook_bak) print(phonebook)
执行结果:
{'Blue': 911, 'customer': 12538, 'Kitty': 123, 'Tim': 120, 'Tom': 110, 'Bob': 119}

浙公网安备 33010602011771号