zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python基础类型之元组

Python基础 类型 元组
2023-09-14 09:15:42 时间

一、元组的介绍

1.Python的元组与列表类似,不同之处在于元组的元素不能修改。
2.元组使用小括号,列表使用方括号。
3.元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

二、元组的使用

# tuple 元组,特点是不可变得列表
m = ("张三", "李四", "王保长")
print(m)
print(m[1:3])
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/12_元组.py
('张三', '李四', '王保长')
('李四', '王保长')

Process finished with exit code 0

三、元组不可变特性

1.不可修改

m = ("张三", "李四", "王保长")
m[0] = "赵敏"  #'tuple' object does not support item assignment
#元组对象对象不支持元素修改
D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/12_元组.py
Traceback (most recent call last):
  File "D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/12_元组.py", line 9, in <module>
    m[0] = "赵敏"  #
TypeError: 'tuple' object does not support item assignment

Process finished with exit code 1

2.元组的第一层不可变

元组内每个元素的内存地址不可变

# 元组的不可变是指第一层的不可变
m = (["张飞", "张辽", "陈宫", "孙尚香", "赵云", ["hcip", "hcip", "hcia"], "于禁", "王平"])
m[5].append("rhce")
print(m)

D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/12_元组.py
['张飞', '张辽', '陈宫', '孙尚香', '赵云', ['hcip', 'hcip', 'hcia', 'rhce'], '于禁', '王平']

Process finished with exit code 0

四、单独元素的使用

a = ("aaaa")   # 单独元素这样写会认为是字符串
print(type(a))
h = ("awaaa",)  # 单独元素,需要加逗号来表示这是一个元组
print(h)
print(type(h))

D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/12_元组.py
<class 'str'>
('awaaa',)
<class 'tuple'>

Process finished with exit code 0