基本数据类型
4、列表(list)
创建列表
name_list = ['zhao','qian','sun','li']
基本操作
- 索引
print(name_list[0]) #返回zhao
print(name_list[1]) #返回qian
- 切片
print(name_list[0:2]) #返回['zhao', 'qian']
- 长度
print len(name_list) #返回4
- 循环
for i in name_list:
print i
- 删除一个索引元素
del name_list[1] #删除索引为1的元素
del name_list[1:3] #删除切片1-2的元素
- 包含in
IsContain = 'sun' in name_list
基本用法总结:
name_list.append('aa') #name_list列表追加一个元素,name_list变为['zhao', 'qian', 'sun', 'li', 'aa']
print name_list.count("li") #返回1,统计name_list中,值为li的个数
name_list.extend(['aa','bb','cc']) #name_list列表追加一个列表,name_list变为['zhao', 'qian', 'sun', 'li', 'aa', 'bb', 'cc'],参数必须为可迭代的
print name_list.index('sun',0,3) #在索引0-3之间查找sun,返回索引,第2、3个参数可以省略
name_list.insert(3,'wang') #在第3个索引前面插入wang,name_list变为['zhao', 'qian', 'sun', 'wang', 'li']
name_list.pop(2) #删除索引为2的项目,如果省略则删除最后一项
name_list.remove('sun') #移除name_list中第一个出现的sun,如果sun不存在则抛出ValueError异常
name_list.reverse() #将name_list中的元素顺序翻转,结果['li', 'sun', 'qian', 'zhao']
sort() #等待补充
其他详细功能及代码:
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.
返回第一个值的索引
如果值不存在则抛出ValueError异常
"""
return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__
""" L.insert(index, object) -- insert object before index
在参数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.
按照index索引删除并返回项目(默认最后一个)
如果列表为空或不在范围内,抛出IndexError异常
"""
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.
移除第一个出现的值,
如果Value值没出现那么抛出ValueError异常
"""
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
5、元组(tuple)
元组与列表基本一样,区别是列表可以支持增删改查,而元组不支持增删改
创建元组
name_tuple = ('zhao','qian','sun','li')
#单个元素tuple定义
name_tuple1 = ('zhao',)
基本操作与列表一样
- 索引
- 切片
- 循环
- 长度
- 包含
基本用法总结
print name_tuple.count("li") #返回1,统计name_tuple中,值为li的个数
print name_tuple.index('sun',0,3) #在索引0-3之间查找sun,返回索引,第2、3个参数可以省略
其他详细功能及代码
class 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、字典(无序)
创建字典
不可变的(可哈希的)对象可以作为key值,例如元组可以作为key值,但列表是可变的则不能作为key值
dic = dict{(11,22,33):"ABC"}
person = {'name':'zhangsan','age':19}
常用操作
- 索引
print person['name'] #输出zhangsan
- 新增
dic['name']='zhang' #如果是已经存在的name则修改,如果不存在则增加
dic['hobby']='football' #如果是已经存在的name则修改,如果不存在则增加
- 删除
- 键、值、键值对
- 循环
- 长度
print len(person) #输出2,即person里面有两个键值对
基本用法总结:
person.clear() #清除person中的所有键值对
person1 = person.copy() #浅拷贝,复制出一个新的字典
print person.fromkeys(person,'xx') #产生一个新的字典,结果返回{'age': 'xx', 'name': 'xx'},如果第二个参数省略则返回{'age': None, 'name': None}
print person.get('height',1.8) #person中没有key-heith所以返回第2个参数1.8,如果第二参数省略找不到返回None,如果能够找到返回key对应的value
print person.has_key('name') #返回True,查询person中是否存在该key,存在返回True,不存在返回False
print person.items() #返回键值对元组[('age', 20), ('name', 'zhangsan')]
print person.keys() #返回keys集合['age', 'name']
print person.values() #返回value集合[20, 'zhangsan']
print person.iteritems() #返回一个字典迭代器<dictionary-itemiterator object at 0x0000000003503728>,list(person.iteritems())则返回[('age', 20), ('name', 'zhangsan')]
print person.iterkeys() #返回一个字典迭代器<dictionary-keyiterator object at 0x0000000003813728>,list(person.iterkeys())则返回['age', 'name']
print person.itervalues() #返回一个字典迭代器<dictionary-valueiterator object at 0x0000000002F93728>,list(person.itervalues())则返回[20, 'zhangsan']
v = person.pop('name') #此时v返回name的value值即zhangsan,person移除了name,即变为{'age': 20};如果找不到,且第3个参数省略则抛出KeyError异常
v = person.popitem() #移除最后一组item,person变为{'name': 'zhangsan'},v返回('age', 20),不同的机器删除的结果可能不同,定义为随机删除
v = person.setdefault('height',1.8) #person={'age': 20, 'name': 'zhangsan', 'height': 1.8},height不存在则添加,并且v返回1.8,如果已存在的key则只返回不添加
person.update([('height',180)]) #person={'age': 20, 'name': 'zhangsan', 'height': 180},如果key存在则更新,如果不存在则添加
v = person.viewitems() #person不变,v返回dict_items([('age', 20), ('name', 'zhangsan')])
v = person.viewkeys() #person不变,v返回dict_keys(['age', 'name'])
v = person.viewvalues() #person不变,v返回dict_values([20, 'zhangsan'])
其他详细功能及代码
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.
一个新的列表,keys=S,values=v,v默认为none
"""
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取值,d是默认值 ,省略默认为None"""
""" 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
移除制定的key并且返回相应的value.
如果key没有找到,那么如果制定了d返回参数d,否则抛出KeyError的异常
"""
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.
移除并且作为(key,value)一对元组返回,如果D是空的那么抛出KeyError异常
"""
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
相当于D.get(k,d),并且如果k不在D中那么设置 D(k)=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]
更新D从字典或可迭代的对象E和F
若果E存在并且有一个.keys()的方法,会执行这句:for k in E: D[k] = E[k]
若果E存在并且没有一个.keys()的方法,会执行这句:for (k, v) in E: D[k] = v
无论哪种情况,这会跟随执行这句: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、for循环
for key in person: #单个打印输出key
print key for value in person.values(): #单个打印输出value
print value for item in person.items(): #单个打印输出键值对
print item
2、enumerate可为迭代的对象添加序号
li = ['zhao','qian','sun','li']
for key,value in enumerate(li): #enumeraate在循环的时候自动添加0开始自增1的key
print key,value
结果:
0 zhao
1 qian
2 sun
3 li
3、range和xrange
range和xrange用来生成制定范围内的数
python2.x中range会直接在内存中生成序列,而xrange是通过迭代的方式实现,在遍历的时候才生成,所以xrange速度更快,在产生非常大的数字范围时,建议用xrange
python3.x中取消xrange,但其range变为通过迭代的方式实现
利用range实现遍历列表:
li = ['zhao','qian','sun','li']
for i in range(0,len(li)):
print li[i]
for i in range(10,0,-1):
print(i)
#输出:10 9 8 7 6 5 4 3 2 1