Python-9 元组-戴上了枷锁的列表
来源:互联网 发布:两轴伺服运动控制编程 编辑:程序博客网 时间:2024/04/29 19:16
1、元组(tuple):戴上了枷锁的列表
由于和列表是近亲关系,所以元组和列表在实际使用上是非常相似的。
元组是不能随意插入和删除元素的。
● 创建和访问一个元组
>>> tuple1=(1,2,3,4,5,6,7,8)>>> tuple1(1, 2, 3, 4, 5, 6, 7, 8)>>> type(tuple1)<class 'tuple'>>>> tuple1[1]2>>> tuple1[5:](6, 7, 8)>>> tuple1[:5](1, 2, 3, 4, 5)>>> tuple1[1]=3Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> tuple1[1]=3TypeError: 'tuple' object does not support item assignment>>>元组的标识是逗号(,),而不是小括号。
>>> temp = (1)>>> temp1>>> type(temp)<class 'int'>>>> temp2=2,3,4>>> type(temp2)<class 'tuple'>>>>创建空元组。
>>> temp = ()>>> type(temp)<class 'tuple'>>>>如果创建的元组中只有一个元素,要在元素后边加上逗号,确保它是元组。如果没有加逗号就只是普通元素。
>>> temp=(1,)>>> type(temp)<class 'tuple'>>>>
>>> temp = 1,>>> type(temp)<class 'tuple'>>>>
在8*(8,)中的*是重复操作符。得到一个8个8的元组。
>>> 8*(8)64>>> 8*(8,)(8, 8, 8, 8, 8, 8, 8, 8)>>>
● 更新和删除一个元组
插入一个元素时小括号和逗号缺一不可,
>>> temp = ('cisco','lenovo','microsoft','google')>>> temp = temp[:2]+('ibm',)+temp[2:]>>> temp('cisco', 'lenovo', 'ibm', 'microsoft', 'google')>>>插入一个元素的过程是将temp分成两部分,在中间加上新的元素,形成新的元组,再将temp标签贴上。原来的元组是还在的,但是没有标签指向它,Python的回收器会回收它,释放内存。
同样可以用分片的方法删除一个元素。
>>> temp = temp[:2]+temp[3:]>>> temp('cisco', 'lenovo', 'microsoft', 'google')>>>删除整个元组可以使用del语句。
>>> del temp>>> tempTraceback (most recent call last): File "<pyshell#34>", line 1, in <module> tempNameError: name 'temp' is not defined>>>在日常很少使用del删除整个元组,因为Python有回收机制。
● 元组相关的操作符
拼接操作符
>>> temp = ('cisco','microsoft','ibm','nike')>>> temp = temp[:2]+('ikea',)+temp[2:]>>> temp('cisco', 'microsoft', 'ikea', 'ibm', 'nike')>>>
重复操作符
>>> 3*temp('cisco', 'microsoft', 'ikea', 'ibm', 'nike', 'cisco', 'microsoft', 'ikea', 'ibm', 'nike', 'cisco', 'microsoft', 'ikea', 'ibm', 'nike')>>>
关系操作符
>>> temp1=('vinda','intel')>>> temp>temp1False>>> temp1>tempTrue>>>
逻辑操作符
>>> temp2=temp1[:]>>> (temp1==temp2) and (temp1>temp)True>>>
成员操作符
>>> 'cisco' in tempTrue>>>
1 0
- Python-9 元组-戴上了枷锁的列表
- 元组:戴上了枷锁的列表
- 013:元组:戴上了枷锁的列表
- 4.元组tuple:戴上了枷锁的列表
- 元组UPLE:戴上了枷锁的列表--2017/9/3--1
- FishC笔记—13 讲 元组:戴上枷锁的列表
- 【零基础入门学习Python笔记013】元祖:戴上了枷锁的列表
- Python-元组-上了枷锁的列表
- python--列表,元组
- python <列表 元组>
- Python列表、元组
- Python 元组 列表
- python 列表 元组
- python的元组、列表、字典
- Python的列表与元组
- python的列表和元组
- python的列表,元组,集合,字典
- Python列表和元组的使用
- 设备树学习之(二)点灯
- C语言基础(2)
- poj1523
- javase输入输出流易被忽视的细节
- 程序员面试金典——解题总结: 9.12测试 12.6在一个分布式银行系统中,该如何测试一台ATM机?
- Python-9 元组-戴上了枷锁的列表
- C#图解教程 第四章 类的基础
- 欢迎使用CSDN-markdown编辑器
- 拷贝 copy()和deepcopy()
- 图解Linux命令之--hwclock命令
- 使用Jekyll搭建个人博客
- [matlab] eig函数求解矩阵特征值和特征向量
- 关于腾讯云通过ip无法访问搭建的网站(无法访问)
- 2017年热门的9大技术领域