python的組合數據類型及其內置方法說明


python中,數據結構是通過某種方式(例如對元素進行編號),組織在一起數據結構的集合.

python常用的組合數據類型有:序列類型,集合類型和映射類型
    在序列類型中,又可以分為列表和元組,字符串也屬於序列類型
    在集合類型中,主要有集合類型
	在映射類型中,主要有字典類型,字典是可變序列

python中一切皆對象,組合數據類型也是對象,因此python的組合數據類型可以嵌套使用,列表中可以嵌套元組和字典,元組中也可以嵌套和字典,當然字典中也可以嵌套元組和列表,例如:['hello','world',[1,2,3]]

元組,列表以及字符串等數據類型是"有大小的",也即其長度可使用內置函數len()測量
python對象可以具有其可以被調用的特定“方法(函數)”		

列表的常用內置方法

在python中,列表使用[]創建,例如['hello','world','linux','python']
列表是可變序列,其主要表現為:列表中的元素可以根據需要擴展和移除,而列表的內存映射地址不改變	
列表屬於序列類型,可以在python解釋器中使用dir(list)查看列表的內置方法			

append

#在列表的末尾添加元素
L.append(object) -- append object to end
>>> l1=["hello","world"]
>>> l2=[1,2,3,4]
>>> l1.append("linux")
>>> print(l1)
['hello', 'world', 'linux']
>>> l2.append(5)
>>> print(l2)
[1, 2, 3, 4, 5]

clear

#清除列表中的所有元素
L.clear() -> None -- remove all items from L
>>> l1=["hello","world"]
>>> l2=[1,2,3,4]
>>> l1.clear()
>>> print(l1)
[]
>>> l2.clear()
>>> print(l2)
[]

copy

#淺復制
L.copy() -> list -- a shallow copy of L
>>> l1=["hello","world","linux"]
>>> id(l1)
140300326525832
>>> l2=l1.copy()
>>> id(l2)
140300326526024
>>> print(l1)
['hello', 'world', 'linux']
>>> print(l2)
['hello', 'world', 'linux']

count

#返回某個元素在列表中出現的次數
L.count(value) -> integer -- return number of occurrences of value
>>> l1=[1,2,3,4,2,3,4,1,2]
>>> l1.count(1)
2
>>> l1.count(2)
3
>>> l1.count(4)
2

extend

#把另一個列表擴展進本列表中
L.extend(iterable) -- extend list by appending elements from the iterable
>>> l1=["hello","world"]
>>> l2=["linux","python"]
>>> l1.extend(l2)
>>> print(l1)
['hello', 'world', 'linux', 'python']

index

#返回一個元素第一次出現在列表中的索引值,如果元素不存在報錯
L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.
    >>> l1=[1,2,3,4,2,3,4,1,2]
	>>> l1.index(1)
	0
	>>> l1.index(2)
	1
	>>> l1.index(4)
	3
	>>> l1.index(5)
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	ValueError: 5 is not in list

insert

#在這個索引之前插入一個元素
L.insert(index, object) -- insert object before index
	>>> l1=['hello', 'world', 'linux', 'python']
	>>> l1.insert(1,"first")
	>>> print(l1)
	['hello', 'first', 'world', 'linux', 'python']
	>>> l1.insert(1,"second")
	>>> print(l1)
	['hello', 'second', 'first', 'world', 'linux', 'python']

pop

#移除並返回一個索引上的元素,如果是一個空列表或者索引的值超出列表的長度則報錯
L.pop([index]) -> item -- remove and return item at index (default last).Raises IndexError if list is empty or index is out of range.
    >>> l1=['hello', 'world', 'linux', 'python']
	>>> l1.pop()
	'python'
	>>> l1.pop(1)
	'world'
	>>> l1.pop(3)
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	IndexError: pop index out of range

remove

#移除第一次出現的元素,如果元素不存在則報錯
L.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
	>>> l1=['hello', 'world', 'linux', 'python']
	>>> l1.remove("hello")
	>>> print(l1)
	['world', 'linux', 'python']
	>>> l1.remove("linux")
	>>> print(l1)
	['world', 'python']
	>>> l1.remove("php")
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	ValueError: list.remove(x): x not in list

reverse

#原地反轉列表
L.reverse() -- reverse *IN PLACE*
	>>> l1=['hello', 'world', 'linux', 'python']
	>>> id(l1)
	140300326525832
	>>> l1.reverse()####
	>>> print(l1)
	['python', 'linux', 'world', 'hello']
	>>> id(l1)
	140300326525832

sort

#對列表進行原地排序
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
	>>> l1=[1,3,5,7,2,4,6,8]
	>>> id(l1)
	140300326526024
	>>> l1.sort()
	>>> print(l1)
	[1, 2, 3, 4, 5, 6, 7, 8]
	>>> id(l1)
	140300326526024

元組的常用內置方法

元組則使用()創建,例如('hello','world'),元組是不可變序列,其主要表現為元組的元素不可以修改,但是元組的元素的元素可以被修改
元組屬於序列類型,可以在python解釋器中使用dir(tuple)查看元組的內置方法

count

#返回某個元素在元組中出現的次數
T.count(value) -> integer -- return number of occurrences of value
>>> t1=("hello","world",1,2,3,"linux",1,2,3)
>>> t1.count(1)
2
>>> t1.count(3)
2
>>> t1.count("hello")
1

index

#返回元素在元組中出現的第一個索引的值,元素不存在則報錯
T.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present.
>>> t1=("hello","world",1,2,3,"linux")
>>> t1=("hello","world",1,2,3,"linux",1,2,3)
>>> t1.count("hello")
1
>>> t1.index("linux")
5
>>> t1.index(3)
4

字典的常用內置方法

字典屬於映射類型,可以在python解釋器中使用dir(dict)查看字典的內置方法

clear

#清除字典中所有的元素
D.clear() -> None.  Remove all items from D.
>>> dic1={"k1":11,"k2":22,"k3":"hello","k4":"world"}
>>> print(dic1)
{'k3': 'hello', 'k4': 'world', 'k2': 22, 'k1': 11}
>>> dic1.clear()
>>> print(dic1)
{}

copy

#淺復制
D.copy() -> a shallow copy of D
>>> dic1={"k1":11,"k2":22,"k3":"hello","k4":"world"}
>>> id(dic1)
140300455000584
>>> dic2=dic1.copy()
>>> id(dic2)####
140300455000648
>>> print(dic2)
{'k2': 22, 'k4': 'world', 'k3': 'hello', 'k1': 11}

fromkeys(iterable, value=None, /)

#返回一個以迭代器中的每一個元素做健,值為None的字典
Returns a new dict with keys from iterable and values equal to value.
>>> dic1={"k1":11,"k2":"hello"}
>>> dic1.fromkeys([22,33,44,55])
{33: None, 44: None, 22: None, 55: None}
>>> print(dic1)
{'k2': 'hello', 'k1': 11}

get

#查詢某個元素是否在字典中,即使不存在也不會報錯
D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
>>> dic1={'k3': None, 'k2': 'hello', 'k1': 11, 'k4': 'world'}
>>> dic1.get("k3")
>>> value1=dic1.get("k1")
>>> print(value1)
11
>>> value2=dic1.get("k2")
>>> print(value2)
hello
>>> value3=dic1.get("k5")
>>> print(value3)
None

items

#返回一個由每個鍵及對應的值構成的元組組成的列表
D.items() -> a set-like object providing a view on D's items
>>> dic1={"k1":11,"k2":22,"k3":"hello","k4":"world"}
>>> dic1.items()
dict_items([('k3', 'hello'), ('k4', 'world'), ('k2', 22), ('k1', 11)])
>>> type(dic1.items())
<class 'dict_items'>

keys

#返回一個由字典所有的鍵構成的列表
D.keys() -> a set-like object providing a view on D's keys
>>> dic1={"k1":11,"k2":22,"k3":"hello","k4":"world"}
>>> dic1.keys()
['k3', 'k2', 'k1', 'k4']

pop

#從字典中移除指定的鍵,返回這個鍵對應的值,如果鍵不存在則報錯
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
>>> dic1={"k1":11,"k2":22}
>>> dic1.pop("k1")
11
>>> dic1.pop("k2")
22

popitem

#從字典中移除一個鍵值對,並返回一個由所移除的鍵和值構成的元組,字典為空時,會報錯
D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
>>> dic1={"k1":11,"k2":22}
>>> dic1.popitem()
('k2', 22)
>>> dic1.popitem()
('k1', 11)
>>> dic1.popitem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'

setdefault

#參數只有一個時,字典會增加一個鍵值對,鍵為這個參數,值默認為None;后接兩個參數時,第一個參數為字典新增的鍵,第二個參數為新增的鍵對應的值
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
>>> dic1={"k1":11,"k2":"hello"}
>>> dic1.setdefault("k3")
>>> print(dic1)
{'k3': None, 'k2': 'hello', 'k1': 11}
>>> dic1.setdefault("k4","world")
'world'
>>> print(dic1)
{'k3': None, 'k2': 'hello', 'k1': 11, 'k4': 'world'}

update

#把一個字典參數合並入另一個字典,當兩個字典的鍵有重復時,參數字典的鍵值會覆蓋原始字典的鍵值
D.update([E, ]**F) -> None.  Update D from dict/iterable E and 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]
>>> dic1={"k1":11,"k2":"hello"}
>>> dic2={"k3":22,"k4":"world"}
>>> dic1.update(dic2)
>>> print(dic1)
{'k3': 22, 'k2': 'hello', 'k1': 11, 'k4': 'world'}
>>> dic1={"k1":11,"k2":"hello"}
>>> dic2={"k1":22,"k4":"world"}
>>> dic1.update(dic2)
>>> print(dic1)
{'k2': 'hello', 'k1': 22, 'k4': 'world'}

values

#返回一個由字典的所有的值構成的列表
D.values() -> an object providing a view on D's values
>>> dic1={"k1":11,"k2":22,"k3":"hello","k4":"world"}
>>> dic1.values()
['hello', 22, 11, 'world']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM