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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章