Python 常用容器类型

Posted on 2018-03-06 16:58  gamehq  阅读(223)  评论(0)    收藏  举报

 

List 对比 Set  对比 Dicetionary 对比 Tuple

前三者数值是可以改变的,Tuple是不可变的

 

lists []

列表

sets {}

集合(不能有重复的)

dicetionaries {}

字典类型{键值对}

tuples()

元组

 List = [10,12,15]

 Set={1,23,34}

Print(Set)->{1,24,23}

Set={1,1}

Print(set)->{1}

Dict={"Ram":26,"mary"24) 

 Words=("spam","egss")

or

Words="spam","eggs"

 Access:print(list[0])

Print(set) 

Set elements can't be indexed.

Print (dict["ram"]) Print(words[0]) 
 Can contans duplicate elements

 Can't contain duplicate elements.

faster campared to Lists

Can't contain duplicate keys,

but can contain duplicate values. 

 Can coutains duplicate elements,Faster compared to Lists
 List[0]=100 set.add(7)   Dict["ram"]=27 Words[0]="care" ->TypeError
 Mutable Mutable  Mutable   Immutable - Values can't be changed once assigned 
 List = [] Set = set()   Dict = {} Words = () 

Slicing can be done

print(list(1:2))->(12) 

Slicing:Not done.  Slicing:Not done.  Slicing can also be done on tuples 

 Usage:

Use lists if you have a collection of data that doesn't need random access.

Use lists when you need a simple,itrable collection that is modified frequently.

 Usage: 

-Membership testing and the elimination of duplicate entries.

-when you need uniqueness for the elements

 Usage: 

-When you need a logical as sociation b/w key:value pair.

-when you need fast lookup for your data,based om a custom key.

-when your data is being constantly modified.

 Usage: 

Use toples when your data cannot change.

A tuple is used in comibantion with a dictionary, forexample, a tuple might represent a key,because its immutable.