元组

作者: __construct | 来源:发表于2018-08-07 11:14 被阅读0次

与列表的区别

都是有序的集合

  • 元组不可修改

元组的操作

创建元组

tuple1 = ()
tuple2 = tuple()

基本操作

  • 访问元素
tuplue1 = ('a', 'b', 'c', 'd')
print(tuplue1[0])
# a
  • 修改元素(不允许)
  • 删除元素(不允许)
  • 添加元素(不允许)
  • 删除整个元组
tuplue1 = ('a', 'b', 'c', 'd')
del tuplue1
print(tuplue1)
# NameError: name 'tuplue1' is not defined, 删除成功
  • 元组相加
tuplue1 = ('a', 'b', 'c', 'd')
tuplue2 = (1, 2, 3)

print(tuplue1 + tuplue2)
# ('a', 'b', 'c', 'd', 1, 2, 3)
  • 元组相乘法
tuplue1 = ('a', 'b', 'c', 'd')
print(tuplue1 *3)
# ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')
  • 切片操作
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print(tuplue1[0:5])
# ('h', 'e', 'l', 'l', 'o')
  • 成员检测
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print('h' in tuplue1) # True
print(1 in tuplue1)  # False

序列函数

  • len() 检测元组的长度
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print(len(tuplue1))
# 10 
  • max() & min()
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(max(tuple1))  # 9
print(min(tuple1))  #  0
  • tuple() 创建空元组 或者 将其他序列转化为元组

  • 遍历

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
for item in tuple1:
    print(item)

元组内涵/元组推导式

  • 推导式
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')

t = (i for i in tuplue1)  # 结果为一个生成器
print(next(t)) # h

相关文章

  • Python入门:元组

    六、元组 6.1 定义元组 元组和列表相似,列表是[---],元组是(---) 6.2 访问元组 6.3 修改元组...

  • Python 元组

    元组的创建和删除 访问元组元素 修改元组元素 元组推导式 元组与列表的区别

  • python入坑第七天|元组

    废话不多说,今天来学习元组。内容如下: 元组的创建 索引、切片 元组的连接 元组的不可修改性 元组内置函数 元组的...

  • Python元组

    python元组元组和列表的区别在于元组中的元素不能修改 创建元组创建元组用() tuple = ()当元组里只包...

  • Python_4_内置结构-元组-字符串

    1. 元组概念1.1. 元组的特点1.2. 元组的定义1.3. 元组的访问1.4. 元组的查询 2. 命名元组 3...

  • Swift 元组 (Tuple)

    定义元组 获取元组内容 修改元组 元组分解 元组作为函数返回值 通常可以用元组来为函数返回多个返回值。

  • 13、Python集合(set)

    上集回顾: 元组(tuple)定义 元组注意事项 元组妙用 上集学习了元组相关知识,元组和列表类似,但是不能修改。...

  • 3.元组Tuple

    目录0.元组介绍1.元组定义和初始化2.元组元素访问3.命名元组namedtuple 0.元组介绍 元组是不可变对...

  • swift 元组 (Tuple)

    元组的声明 输出结果 元组解包 输出结果 元组的分量 输出结果 命名元组分量 输出结果 使用_忽略元组分量

  • 元组

    目录 元组基本介绍 可变对象 元组和列表的区别 元组的解包(Unpacking) 1. 元组基本介绍 元组表现形式...

网友评论

      本文标题:元组

      本文链接:https://www.haomeiwen.com/subject/psdovftx.html