引言
今天来梳理一下 Python tuple 元组知识点,更多 Python 基础系列文章,请参考 Python 基础系列大纲。
内容提要:
- Tuple 元组特性
- Named tuples
- Tuple 元组操作
Tuple 元组特性
Tuple 元组是一个不可变的异类对象的有序集合
异类 heterogeneous 对象:
tuple 元组的 item 可以是不同类型的
不可变 immutable: 一旦创建,便不可改变(增加,删除,更新) item。
new_tup = (3, 5, 2, 8)
new_tup[0] = 1
# output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-515-0b043ae6152f> in <module>
1 new_tup = (3, 5, 2, 8)
----> 2 new_tup[0] = 1
TypeError: 'tuple' object does not support item assignment
但是 tuple 可以包含 mutable 的元素,而且可以修改 mutable 元素的 value
list_tuple = ([8, 7, 5], [1.8, 7.6, 3.5])
dics_tuple = ({'name':'Lu', 'age':24}, {'car':'BMW', 'y':2015})
print('original list_tuple:\n {}'.format(list_tuple))
print('original dics_tuple:\n {}'.format(dics_tuple))
list_tuple[0][1] = 1
dics_tuple[0]['age'] = 30
print('list_tuple after chang:\n {}'.format(list_tuple))
print('dics_tuple after change:\n {}'.format(dics_tuple))
# output:
original list_tuple:
([8, 7, 5], [1.8, 7.6, 3.5])
original dics_tuple:
({'name': 'Lu', 'age': 24}, {'car': 'BMW', 'y': 2015})
list_tuple after chang:
([8, 1, 5], [1.8, 7.6, 3.5])
dics_tuple after change:
({'name': 'Lu', 'age': 30}, {'car': 'BMW', 'y': 2015})
Named Tuples
这个应用非常广泛,类似定义一个类,可以通过属性名去访问属性值,不用专门去定义一个类。
- 通过名字而不是数字的 index 访问 items
- 通过
namedtuple()
函数来创建
namedtuple(‘class name’, ‘the attibute of the class’)
from collections import namedtuple
Pet = namedtuple('Pet', 'kind name age')
dog = Pet(kind='dog', name='Tom', age=2)
cat = Pet(kind='cat', name='Snow', age=3)
print ('dog pet:\nkind:{}\tname:{}\tage:{}'.format(dog.kind, dog.name, dog.age))
print ('cat pet:\nkind:{}\tname:{}\tage:{}'.format(cat.kind, cat.name, cat.age))
# output:
dog pet:
kind:dog name:Tom age:2
cat pet:
kind:cat name:Snow age:3
Tuple 元组操作
Operation | Description | Result |
---|---|---|
len() | tuple 元组 item 个数 | len(tup_1) |
Concatenation(+) | 将两个 tuples 拼接成一个新的 tuple | tup_1 + tup_2 |
Membership check (in) | 检查 item 是否在 tuple 中 | 8 in tup_1 |
Repetition (*) | 复制操作 | (‘A’,) * 3 |
举例:
tup_1 = (5, 8, 9)
tup_2 = (4, 3)
print (len(tup_1))
print (tup_1 + tup_2)
print (8 in tup_1)
print (tup_2 * 3)
# output:
3
(5, 8, 9, 4, 3)
True
(4, 3, 4, 3, 4, 3)
Tuple 元组访问和切片
nums = (0, 1, 2, 3, 4, 5, 6, 7)
print(nums[4])
print(nums[-5])
print(nums[:3])
print(nums[-6:-3])
print(nums[7:1:-2])
# output:
4
3
(0, 1, 2)
(2, 3, 4)
(7,5,3)
Tuple 元组创建
-
创建空 tuple 元组:
t = ()
t = tuple() -
tuple(another_object)–有些python版本可能不支持
t1 = ('a',)
list_obj=[1,2,3,4,5,6]
t2 = tuple(list_obj)
t3 = 'a', 2, ['one', 'two']
t4 = tuple()
t4 = t4 + tuple('one')
print(t1)
print(t2)
print(t3)
print(t4)
# output:
('a',)
(1, 2, 3, 4, 5, 6)
('a', 2, ['one', 'two'])
('o', 'n', 'e')
count(value)
返回元组中 value 出现的次数
t = (2,1,2,3,4,2)
print(t.count(2)) #output: 3
index(value)
返回元组中 value 第一次出现的位置
t = (2,1,2,3,4,2)
print(t.index(2)) #output 0