zoukankan      html  css  js  c++  java
  • 【Python基础】09_Python中的元组

    1.元组的定义

    • Tuple (元组)与列表类似,元组的元素 不能修改
    • 元组通常保存 不同类型 的数据
    • 元组用()定义
    • info_tuple = ("张三", 18, 1.75)

    定义

    元组名 = (元素1, 元素2, 元素3)

    2.元组的创建

    • 空元组   元组名 = () ,很少使用,因为定义后,元组无法修改
    • 只有一个元素的元组元组名 = (元素1,) 注:元素后 必须 添加 ,  逗号否则创建的是一个变量

    3.元组的常用操作

    1 # 定义一个元组
    2 info_tuple = ("张三", 18, 1.75)
    3 print(info_tuple)  # ('张三', 18, 1.75)
    4 print(info_tuple[1])  # 18
    5 print(info_tuple.index(18))  # 1
    6 print(info_tuple.count("张三"))  # 1 (计算某个元组在元组中的个数)

    4.元组和格式化字符串

     格式化字符串后面的(),本质上就是一个元组

    1 print("%s 年龄是 %d 身高是 %.2f " % ("张三", 18, 1.75))
    1 info_tuple = ("张三", 18, 1.75)
    2 print("%s 年龄是 %d 身高是 %.2f " % info_tuple)  # 张三 年龄是 18 身高是 1.75 
    1 info_str = "%s 年龄是 %d 身高是 %.2f " % info_tuple
    2 print(info_str)  # 张三 年龄是 18 身高是 1.75

    5.元组和列表之间的转换

    • list(元组)
    • tuple(列表)
    1 info_tuple = ("张三", 18, 1.75)
    2 print(list(info_tuple))  # ['张三', 18, 1.75]
    3 info_list = ["张三"]
    4 print(tuple(info_list))  # ('张三',)
  • 相关阅读:
    BFS(从数字A变到数字B每次只能换一个数)
    BFS(数字a通过三种操作到数字B)
    dfs+bfs(三种路径问题)
    国际象棋跳马问题
    拓扑排序
    hadoop-hdfs、mapreduce学习随笔
    hive初探2_数据模型
    hive初探_框架组成、简单使用
    Scala学习笔记
    Scala安装
  • 原文地址:https://www.cnblogs.com/dujinyang/p/11261176.html
Copyright © 2011-2022 走看看