【python之路8】python基本数据类型(二)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【python之路8】python基本数据类型(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                基本數據類型
4、列表(list)
創(chuàng)建列表
name_list = ['zhao','qian','sun','li']基本操作
- 索引
?
- 切片
- 長度
- 循環(huán)
- 刪除一個索引元素
- 包含in
基本用法總結:
name_list.append('aa') #name_list列表追加一個元素,name_list變?yōu)閇'zhao', 'qian', 'sun', 'li', 'aa'] print name_list.count("li") #返回1,統(tǒng)計name_list中,值為li的個數 name_list.extend(['aa','bb','cc']) #name_list列表追加一個列表,name_list變?yōu)閇'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變?yōu)閇'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 listlist(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 添加一個對象到最后"""passdef count(self, value): # real signature unknown; restored from __doc__""" L.count(value) -> integer -- return number of occurrences of value 返回出現值的數量"""return 0def extend(self, iterable): # real signature unknown; restored from __doc__""" L.extend(iterable) -- extend list by appending elements from the iterable 通過增加可迭代的元素擴展列表"""passdef 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 0def insert(self, index, p_object): # real signature unknown; restored from __doc__""" L.insert(index, object) -- insert object before index 在參數index的前面插入對象"""passdef 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異常"""passdef 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異常"""passdef reverse(self): # real signature unknown; restored from __doc__""" L.reverse() -- reverse *IN PLACE* 位置反序排列"""passdef 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位置穩(wěn)定正序排序"""passdef __add__(self, y): # real signature unknown; restored from __doc__""" x.__add__(y) <==> x+y """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x """passdef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __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."""passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __getslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __iadd__(self, y): # real signature unknown; restored from __doc__""" x.__iadd__(y) <==> x+=y """passdef __imul__(self, y): # real signature unknown; restored from __doc__""" x.__imul__(y) <==> x*=y """passdef __init__(self, seq=()): # known special case of list.__init__"""list() -> new empty listlist(iterable) -> new list initialized from iterable's items# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """passdef __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 """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __reversed__(self): # real signature unknown; restored from __doc__""" L.__reversed__() -- return a reverse iterator over the list """passdef __rmul__(self, n): # real signature unknown; restored from __doc__""" x.__rmul__(n) <==> n*x """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __setslice__(self, i, j, y): # real signature unknown; restored from __doc__"""x.__setslice__(i, j, y) <==> x[i:j]=yUse of negative indices is not supported."""passdef __sizeof__(self): # real signature unknown; restored from __doc__""" L.__sizeof__() -- size of L in memory, in bytes """pass__hash__ = None5、元組(tuple)
元組與列表基本一樣,區(qū)別是列表可以支持增刪改查,而元組不支持增刪改
創(chuàng)建元組
name_tuple = ('zhao','qian','sun','li') #單個元素tuple定義 name_tuple1 = ('zhao',)基本操作與列表一樣
- 索引
- 切片
- 循環(huán)
- 長度
- 包含
基本用法總結
print name_tuple.count("li") #返回1,統(tǒng)計name_tuple中,值為li的個數 print name_tuple.index('sun',0,3) #在索引0-3之間查找sun,返回索引,第2、3個參數可以省略其他詳細功能及代碼
class tuple(object):"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf 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 0def 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 0def __add__(self, y): # real signature unknown; restored from __doc__""" x.__add__(y) <==> x+y """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __hash__(self): # real signature unknown; restored from __doc__""" x.__hash__() <==> hash(x) """passdef __init__(self, seq=()): # known special case of tuple.__init__"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object.# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """passdef __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 """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __rmul__(self, n): # real signature unknown; restored from __doc__""" x.__rmul__(n) <==> n*x """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" T.__sizeof__() -- size of T in memory, in bytes """passtuple
6、字典(無序)
創(chuàng)建字典
person = {'name':'zhangsan','age':19}常用操作
- 索引
- 新增
- 刪除
- 鍵、值、鍵值對
- 循環(huán)
- 長度
基本用法總結:
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,即變?yōu)閧'age': 20};如果找不到,且第3個參數省略則拋出KeyError異常 v = person.popitem() #移除最后一組item,person變?yōu)閧'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 dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin 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. 移除所有的項目"""passdef copy(self): # real signature unknown; restored from __doc__""" 淺拷貝 """""" D.copy() -> a shallow copy of D """pass@staticmethod # known casedef 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"""passdef 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. """passdef 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 Falsedef 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 """passdef iterkeys(self): # real signature unknown; restored from __doc__""" key可迭代 """""" D.iterkeys() -> an iterator over the keys of D """passdef itervalues(self): # real signature unknown; restored from __doc__""" value可迭代 """""" D.itervalues() -> an iterator over the values of D """passdef 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的異常"""passdef popitem(self): # real signature unknown; restored from __doc__""" 獲取并在字典中移除 """"""D.popitem() -> (k, v), remove and return some (key, value) pair as a2-tuple; but raise KeyError if D is empty.移除并且作為(key,value)一對元組返回,如果D是空的那么拋出KeyError異常"""passdef setdefault(self, k, d=None): # real signature unknown; restored from __doc__""" 如果key不存在,則創(chuàng)建,如果存在,則返回已存在的值且不修改 """""" 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"""passdef 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] = vIn either case, this is followed by: for k in F: D[k] = F[k]更新D從字典或可迭代的對象E和F若果E存在并且有一個.keys()的方法,會執(zhí)行這句:for k in E: D[k] = E[k]若果E存在并且沒有一個.keys()的方法,會執(zhí)行這句:for (k, v) in E: D[k] = v無論哪種情況,這會跟隨執(zhí)行這句:for k in F: D[k] = F[k]"""passdef 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 """passdef viewkeys(self): # real signature unknown; restored from __doc__""" D.viewkeys() -> a set-like object providing a view on D's keys """passdef viewvalues(self): # real signature unknown; restored from __doc__""" D.viewvalues() -> an object providing a view on D's values """passdef __cmp__(self, y): # real signature unknown; restored from __doc__""" x.__cmp__(y) <==> cmp(x,y) """passdef __contains__(self, k): # real signature unknown; restored from __doc__""" D.__contains__(k) -> True if D has a key k, else False """return Falsedef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __init__(self, seq=None, **kwargs): # known special case of dict.__init__"""dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin the keyword argument list. For example: dict(one=1, two=2)# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __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 """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" D.__sizeof__() -> size of D in memory, in bytes """pass__hash__ = Nonedict其他:
1、for循環(huán)
for key in person: #單個打印輸出keyprint keyfor value in person.values(): #單個打印輸出valueprint valuefor item in person.items(): #單個打印輸出鍵值對print item2、enumerate可為迭代的對象添加序號
li = ['zhao','qian','sun','li'] for key,value in enumerate(li): #enumeraate在循環(huán)的時候自動添加0開始自增1的keyprint key,value 結果: 0 zhao 1 qian 2 sun 3 li3、range和xrange
range和xrange用來生成制定范圍內的數
python2.x中range會直接在內存中生成序列,而xrange是通過迭代的方式實現,在遍歷的時候才生成,所以xrange速度更快,在產生非常大的數字范圍時,建議用xrange
python3.x中取消xrange,但其range變?yōu)橥ㄟ^迭代的方式實現
利用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
轉載于:https://www.cnblogs.com/sunshuhai/p/6265368.html
總結
以上是生活随笔為你收集整理的【python之路8】python基本数据类型(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 终于写了自己第一个有些用处的代码,留念留
- 下一篇: bios 不正常启动怎么办 bios启动
