1. 程式人生 > >python基本數據類型(二)-python3.0學習筆記

python基本數據類型(二)-python3.0學習筆記

tin 基本數據 abcde 返回 屬性方法 mat sizeof 不可變 map

python基本數據類型

序列類型的自帶方法

1.列表的常用方法

2.元祖的常用方法

3.字符串的常用方法

1.列表常用的方法

L.append(obj)       #在列表末尾添加新的對象
L.clear()           #清空列表
L.copy()            #復制列表,不是同一個對象,內容相同,有返回值。id不同(內存中的地址不同)
L.count(obj)        #統計某個元素在列表中出現的次數
L.extend(obj)       #用obj擴展原來的列表
L.index(obj)        #默認值返回這個元素最先出現的索引位置;需要出現下一個位置的,添加可選參數start,stop。
Linsert(index,obj)  #插入元素,可以指定位置
L.pop(index)        #出棧,可以指定位置。index,默認是L[-1],按索引刪除
L.remove(obj)       #移除指定元素從左邊開始第一個
L.reverse()         #反向列表元素
L.sort()            #對列表進行排序(默認ACSII)。列表中的元素要類型相同(key=len)

內置函數:
sorted()和reversed()

>>> li = [1,2,3]
>>> dir(li) #查看li列表的屬性方法,帶下劃線的為魔法方法和私有方法,不用管。學習其它的。
[‘__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_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
#那些方法對列表做了不可描述的方法
>>> help(li)        #列出所有方法
>>> help(li.append) #查看li的append的用法
Help on built-in function append:

append(...) method of builtins.list instance
    L.append(object) -> None -- append object to end  #添加對象返回空值,在原列表的末尾添加
>>> li.append(4)
>>> li
[1, 2, 3, 4]
>>> li.clear()
>>> li
[]
>>> li = [1,2,3]
>>> id(li)
54036680
>>> li2 = li.copy()
>>> li2
[1, 2, 3]
>>> id(li2)
54636232
>>> li.count(2)
1
>>> li.append(2)
>>> li.count(2)
2
>>> li
[1, 2, 3, 2]
>>> li.extend("456")
>>> li
[1, 2, 3, 2, ‘4‘, ‘5‘, ‘6‘]
>>> li = [1,2,3]
>>> li.extend([4,5,6])
>>> li
[1, 2, 3, 4, 5, 6]
>>> li.extend((7,8))
>>> li
[1, 2, 3, 4, 5, 6, 7, 8]
>>> li
[1, 2, 3, 4, 5, 6, 7, 8]
>>> li.index(7)
6
>>> li = [‘a‘,‘b‘,‘c‘,‘d‘]
>>> li.index(‘c‘)
2
>>> help(li.index)
Help on built-in function index:

index(...) method of builtins.list instance
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

>>> li = [‘a‘,‘b‘,‘c‘,‘d‘,‘c‘]
>>> li.index(‘c‘)
2
>>> li.index(‘c‘,3)
4
>>> li.index(‘c‘,3,5)
4
>>> li.index(‘c‘,3,6)
4
>>> help(li.insert)
Help on built-in function insert:

insert(...) method of builtins.list instance
    L.insert(index, object) -- insert object before index
>>> li
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘c‘]
>>> li.insert(1,‘lucky‘)
>>> li
[‘a‘, ‘lucky‘, ‘b‘, ‘c‘, ‘d‘, ‘c‘]
>>> li.insert(-1,‘qq‘)
>>> li
[‘a‘, ‘lucky‘, ‘b‘, ‘c‘, ‘d‘, ‘qq‘, ‘c‘]
>>> help(li.pop)
Help on built-in function pop:

pop(...) method of builtins.list instance
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.

>>> li.pop(1)
‘lucky‘
>>> li
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘qq‘, ‘c‘]
>>> li.pop()
‘c‘
>>> li
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘qq‘]
>>> help(li.remove)
Help on built-in function remove:

remove(...) method of builtins.list instance
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.

>>> li
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘qq‘]
>>> li.remove(‘c‘)
>>> li
[‘a‘, ‘b‘, ‘d‘, ‘qq‘]
>>> help(li.reverse)
Help on built-in function reverse:

reverse(...) method of builtins.list instance
    L.reverse() -- reverse *IN PLACE*
>>> li.reverse()
>>> li
[‘c‘, ‘d‘, ‘b‘, ‘a‘]
>>> help(li.sort)
Help on built-in function sort:

sort(...) method of builtins.list instance
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

>>> li.sort()
>>> li
[‘a‘, ‘b‘, ‘c‘, ‘d‘]
>>> li = [‘a‘,‘c‘,‘ab‘]
>>> li.sort()
>>> li
[‘a‘, ‘ab‘, ‘c‘]
>>> li.sort(key=len)        #按照長度相等的排序然後再按不等的排序
>>> li
[‘a‘, ‘c‘, ‘ab‘]
>>> li.sort(key=len,reverse=True)
>>> li
[‘ab‘, ‘a‘, ‘c‘]
函數reversed和sorted:
>>> reversed(li)   #返回一個叠代器
<list_reverseiterator object at 0x00000000033C2978>
>>> list(reversed(li))
[‘c‘, ‘a‘, ‘ab‘]
>>> sorted(li)
[‘a‘, ‘ab‘, ‘c‘]
可變特點:
>>> li = [2,3]
>>> id(li)
53901000
>>> li.append(4)
>>> id(li)
53901000
>>> li.pop()
4
>>> id(li)
53901000

2.元祖的常用方法

count(obj)          #統計某個元素在元祖中出現的次數
index(obj)          #從列表中找到某個值第一個匹配項的索引位置
註意:生命只有一個元素的元組時要加逗號
特點:不可變

舉例:
>>> tu = 1,2
>>> dir(tu)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘count‘, ‘index‘]
>>> tu.count(1)
1
>>> tu.count(3)
0
>>> help(tu.index)
Help on built-in function index:

index(...) method of builtins.tuple instance
    T.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
>>> tu.index(1)
0

3.字符串的常用方法

s.count(x)          #返回字符串x在s中出現的次數,可帶參數
s.endswith(x)       #如果字符串s以x結尾,返回True
s.startswith(x)     #如果字符串s以x開頭,返回True
s.find(x)           #返回字符串中出現x的最左端字符的索引值,如不在則返回-1
s.index(x)          #返回字符串中出現x的最左端的索引值,如不在則拋出valueError異常
s.isalpha()         #測試是否全為字母,都是則True;否則False
s.isdigit()         #測試是否全是數字,都是則True;否則False
s.islower()         #測試全是小寫
s.isupper()         #測試全是大寫
s.lower()           #將字符串轉為小寫
s.upper()           #將字符串轉為大寫
s.replace(x,y)      #字串替換,在字符串s中出現字符串x的任意位置都用y進行替換
s.split()           #返回一系列用空格分割的字符串列表
s.split(a,b)        #a,b為可選參數,a是將要分割的字符串,b是說明最多分割幾個。

舉例:
>>> s=‘‘
>>> dir(s)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
>>> s.count(‘3‘)
0
>>> help(s.endswith)
Help on built-in function endswith:

endswith(...) method of builtins.str instance
    S.endswith(suffix[, start[, end]]) -> bool

    Return True if S ends with the specified suffix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.

>>> s=‘abcde‘
>>> s.endswith(‘a‘)
False
>>> s.endswith(‘e‘)
True
>>> help(s.startswith)
Help on built-in function startswith:

startswith(...) method of builtins.str instance
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.

>>> s.startswith(‘a‘)
True
>>> help(s.find)
Help on built-in function find:

find(...) method of builtins.str instance
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

>>> s.find(‘v‘)         #不存在的值
-1
>>> s.find(‘b‘)
1
>>> help(s.index)
Help on built-in function index:

index(...) method of builtins.str instance
    S.index(sub[, start[, end]]) -> int

    Like S.find() but raise ValueError when the substring is not found.

>>> s.index(‘e‘)     #默認返回最先出現的位置
4
>>> s=‘abcde‘
>>> s.isalpha()     #測試全是字母
True
>>> s.isdigit()     #測試全是數字,只能測試正整數,負數返回-1
False
>>> s.islower()     #測試全是小寫
True
>>> s.isupper()     #測試全是大寫
False
>>> s1 = ‘12AA‘
>>> s1.isupper()
True
>>> s1.upper()      #全部改成大寫
‘12AA‘
>>> s1.lower()      #全部改成小寫
‘12aa
>>> help(s.replace)
Help on built-in function replace:

replace(...) method of builtins.str instance
    S.replace(old, new[, count]) -> str

    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
>>> s1.replace(‘12‘,‘bb‘)       #將舊元素替換成新的元素。替換次數的參數可選
‘bbAA‘
>>> s1.replace(‘A‘,‘b‘,1)
‘12bA‘
>>> help(s.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.
>>> s.split(sep=‘o‘)
[‘i l‘, ‘ve pyth‘, ‘n‘]
>>> s.split(maxsplit=1)
[‘i‘, ‘love python‘]
>>> s.split(‘1‘)
[‘i love python‘]
>>> s.split(sep=‘o‘,maxsplit=1)
[‘i l‘, ‘ve python‘]
>>> s=‘123‘
>>> s.split(sep=‘1‘)
[‘‘, ‘23‘]

python基本數據類型(二)-python3.0學習筆記