美文网首页
Python 元组

Python 元组

作者: lc_666 | 来源:发表于2020-04-01 10:25 被阅读0次
  • tuple [tjʊpəl; ˈtʌpəl]
  • 定义符号:()
  • 元组内容不可修改;
  • 元组中只有一个元素定义需要加,t1 = ('hello',);否则括号会被当作运算符使用;
  • +、*、in、not in、is都可以用于元组;
  • 使用sorted()回返回一个列表类型;

将list转为tuple

  • 强转方法:tuple()
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
print(t1)#(1, 2, 3, 4, 5)
print(type(t1))#<class 'tuple'>

查询

使用下表获取元素

l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
print(t1[0])#1

使用切片获取元素

  • 类似于list的用法;
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
print(t1[0:2])#(1, 2)

获取最大值 最小值 求和 长度

l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
print(max(t1), min(t1), sum(t1), len(t1))
#5 1 15 5

内置函数

  • index():获取元素下标,不存在元素会报ValueError
  • count():获取元组中元素的个数;
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
print(t1.index(2))
print(t1.count(3))
# 1 1

删除

  • 使用del来删除整个元组;
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
del t1
print(t1)
#    print(t1)
#NameError: name 't1' is not defined

拆包

  • 使用:
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
a, b, c, d, e = t1

变量个数与元组个数不同

  • 使用*b来代表未知个数的元素,放到一个列表中;
l1 = [1, 2, 3, 4, 5]
t1 = tuple(l1)
a, *b, e = t1
print(a,b,e)
#1 [2, 3, 4] 5

相关文章

  • Python基础之元组、字典,集合详解

    之前总结了Python列表,这篇总结Python的元组,字典和集合。 一 元组 tuple Python 的元组与...

  • Python 元组

    Python 元组 Python的元组与列表类似,不同之处在于元组的元素不能修改。 1.1 定义元组使用小括号,列...

  • Lesson 016 —— python 元组

    Lesson 016 —— python 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改。 ...

  • python小课堂08 - 基本数据类型元组篇

    python小课堂08 - 基本数据类型元组篇 python中的元组 python中的元组,也是作为基础数据类型之...

  • python 基础 - 元组

    Python 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号...

  • 元祖

    Python 元组 Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。...

  • Python元组常用方法

    一、前言? ✔本文是Python元组常用方法总结Python的元组与列表类似,不同之处在于元组的元素不能修改,元组...

  • 学习python第六天总结

    一python的基本类型 元组 python 的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列...

  • Python中的tuple元组

    Python中的tuple元组 一、访问元组 Python中的元组和列表类似,不同之处在于元组中的元素不能够被修改...

  • Python 元组

    Python中,元组的操作与列表相似,不同点是元组是不可变对象,元组中的元素不能修改。 1、定义元组 Python...

网友评论

      本文标题:Python 元组

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