Tuples (元组)
元组(tuple)和列表(list)都是容器类型(container type)。元组与列表的区别如下图所示。
元组的增删改查
- 元组的创建与赋值(增)
创建元组就列表的创建是一样,就像给变量赋值一样。创建方法有两种:
- 元组可以用
(,)
来定义- 元组可以用工厂方法
tuple()
来创建。
Note: 只有一个元素的元组在创建时候必须要加一个逗号(,)
举例说明:
>>> aTuple = (123, 'abc', 4.56, ['inner', 'tuple'], 7-9j)
>>> anotherTuple = (None, 'something to see here')
>>> print(aTuple)
(123, 'abc', 4.56, ['inner', 'tuple'], (7-9j)
>>> print(anotherTuple)
(None, 'something to see here')
>>>
>>> singleItemTuple = (None,)
>>> print singleItemTuple(None,)
>>> tuple('bar') #自己比较与tuple(['bar'])的区别
('b', 'a', 'r')
单元素元组的问题,比如有无逗号的问题。测试结果如下
>>> ('xyz')
'xyz'
>>> type(('xyz'))# a string, not a tuple
<type 'str'>
>>>
>>># 因为overload的问题,所以务必加逗号
>>> ('xyz',)
('xyz',)
- 元组的访问(查)
跟列表一样可以[]
来切片。
举例说明:
>>> aTuple = (123, 'abc', 4.56, ['inner', 'tuple'], 7-9j)
>>> aTuple[1:4]
('abc', 4.56, ['inner',