Member-only story

[Python] Python資料結構的比較

Jack in the world
3 min readSep 18, 2019

--

Python的常用資料結構有以下幾種

  • List
  • tuple
  • dict
  • set
  • frozenset
  • string
  • range

List

  • Lists用[]
  • 內容可以更改(Mutable)
  • Sequence type,有序(Ordered),所以可以用index來存取
  • 可以用來實作Stack(堆疊)或是Queue(佇列),不過通常使用collections.deque來實作Queue會比較方便
  • 通常用iterating的方式來存取
  • 可以有重複元素(跟Set的最大不同)

Truple

  • Truples用()
  • 內容不可更改(Immutable)
  • 類似List,因為不能更改內容,所以在實作上會比List快
  • Sequence type
  • 跟List的差別是:通常包含異質(heterogeneous)的元素,也就是說,Truple的元素可以是不同資料型態
  • 通常用indexing或是unpacking的方式來取得元素

Dict

  • Dicts用{}
  • 內容可以更改
  • Not Sorted,雖然可以認為元素是按照插入的順序,不過還是小心為上
  • Mapping type
  • 每個元素都有keyvalue ,key就是index,可以是各種immutable的資料型態,在一個dict中必須是unique的數值
  • 通常用來實作hasbtable

Set

  • Sets用set()來initialized,如果不是空的set可以用{},之後以{}來顯示內容
a_set = set([1, 2, 3])
# a_set is now {1, 2, 3}
  • Unordered
  • 內容可以更改
  • 沒有重複元素
  • 有些操作方法類似集合的運算,譬如

--

--

Jack in the world
Jack in the world

Written by Jack in the world

Where in the world is Jack? 在這個世界上, 我們都在找尋自己的所在. 寫程式是我的嗜好和工作, 好好地生活在這個世界是我的日常, 學習新知識是我的快樂.

No responses yet