puthon基礎實戰(四)-Tuple

python中常用的Contailer Types(類型)有四個:

  • List
  • Tuple
    Similar to lists, tuples are also sequences of arbitrary items. However, tuples are immutable. You can not add, detele or change it after it is defined.
  • Dictionary
  • Set

上篇博客對list瞭解了一下,本篇則對Tuple學習一下。List是可以對其進行增刪改操作,利用的符號是[],而Tuple則沒有那麼大的活動性,一旦創建,則不能再進行增刪改操作。利用的符號是()。

Create Tuple

empty_tuple=()
empty_tuple

week_tuple=('Monday','Tuesday')
week_tuple

#()代表的則是一個tuple,可直接輸出
(123,456,789)

single_tuple=('Monday',)
single_tuple
type(single_tuple)

huohuo_tuple=('huohuo','Male',20)
name,gender,age=huohuo_tuple
print('name=',name,",gender=",gender,",age=",age)

//輸出結果
()

('Monday', 'Tuesday')

(123, 456, 789)

('Monday',)
tuple

name= huohuo ,gender= Male ,age= 20

Tuple vs List

tuple不可變是有很大的好處的。

  • 相對於 list 而言,tuple 是不可變的,這使得它可以作爲 dict 的 key,或者扔進 set 裏,而 list 則不行。
  • tuple 放棄了對元素的增刪(內存結構設計上變的更精簡),換取的是性能上的提升:創建 tuple 比 list 要快,存儲空間比 list 佔用更小。所以就出現了“能用 tuple 的地方就不用 list”的說法。
  • 多線程併發的時候,tuple 是不需要加鎖的,不用擔心安全問題,編寫也簡單多了。
single_tuple=('Monday',)
single_tuple
type(single_tuple)

# 創建單個元素的元組,','是必不可少的。通過兩個類型就能夠判定逗號的重要性
single_tuple1=('Monday')
single_tuple1
type(single_tuple1)

//輸出結果
('Monday',)
tuple
'Monday'
str
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章