Python__17--元组

简介: 元组

Untitled.png (2000×964) (amazonaws.com)

1 元组

Python的元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组使用圆括号包含元素,而列表使用方括号包含元素。元组的创建,只需在圆括号中添加元素并使用逗号分开即可。与字符串的索引类似,元组的索引也是从0开始。

不能改变的列表。

1.1 元组是不可变序列

https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7b51772a40e848629612d8ba0990fef4~tplv-k3u1fbpfcp-zoom-1.image

  1. 不可变序列:字符串、元组

    没有增删改,或者说增删改后地址变了

  2. 可变序列:列表、字典、集合

    可以增删改,对象地址不发生更改

1.2 元组的创建

1.2.1 使用(),括号可以省略

  • t=('Python‘,'World',98)

    t=('Python','World',98)
    print(t)
    print(type(t))
    #输出为
    #('Python‘,'World',98)
    #<class'tuple'>
  • t=(10,)

    • 单个元素必须加逗号和括号

1.2.2 使用内置函数tuple()

  • t=tuple(('Python','World',98))

1.2.3 创建空

  • 空列表

    • lst=[]
    • lst1=list()
  • 空字典

    • d={}
    • d1=dict()
  • 空元组

    • t=()
    • t=tuple()
  • 空集合

    • s=set()

1.3 元组元素获取

  1. print(t[0])、print(t[1])
  2. 元组的遍历

    for item in t:
        print(item)

1.4 测试

测试代码:

t=('Python','World',98)
print(t)
print(type(t))
t=(10,)
print(t)
print(type(t))
t='Python','World',98
print(t)
print(type(t))
t=(10)
print(t)
print(type(t))
t=tuple(('Python','World',98))
print(t)
print(type(t))
print(t[0])
for item in t:
    print(item)

测试结果:

tmpA890.png (255×453) (amazonaws.com)

相关文章
|
7天前
|
存储 索引 Python
元组(Tuple)在Python编程中的应用与实例
元组(Tuple)在Python编程中的应用与实例
21 2
|
17天前
|
存储 索引 Python
Python 元组
Python 元组
23 0
|
3天前
|
索引 Python
7.Python【序列】- 元组
7.Python【序列】- 元组
|
5天前
|
Python 索引
|
7天前
|
存储 索引 Python
Python元组的定义与操作详解
Python元组的定义与操作详解
4 1
|
8天前
|
存储 索引 Python
Python元组
Python元组
14 0
|
10天前
|
数据处理 Python
深入理解Python的数据结构:列表与元组
深入理解Python的数据结构:列表与元组
25 1
|
10天前
|
存储 索引 Python
Python元组
Python元组
|
17天前
|
存储 数据处理 索引
Python基础教程——元组
Python基础教程——元组
|
17天前
|
索引 Python
Python数据结构——元组
Python数据结构——元组
20 0