• python学习-18 元组


    tuple

    1.元组tuple类似列表,由小括号()括住,其中的元素不可被修改,不能被增加或删除

    tu = (222,222123123,("小胡子",444),12341,"你好啊",["小明",123],)
    print(tu)

    运行结果:

    (222, 222123123, ('小胡子', 444), 12341, '你好啊', ['小明', 123])
    
    Process finished with exit code 0

    ps:建议在最后加一个逗号,便于分辨(不会报错,但列表会)

    2.取值

    通过索引:

    tu = (222,222123123,("小胡子",444),12341,"你好啊",["小明",123],)
    a = tu[0]
    print(a)

    运行结果:

    222
    
    Process finished with exit code 0

    通过切片:

    tu = (222,222123123,("小胡子",444),12341,"你好啊",["小明",123],)
    a = tu[0:5]
    print(a)

    运行结果:

    (222, 222123123, ('小胡子', 444), 12341, '你好啊')
    
    Process finished with exit code 0

    for循环:

    tu = (222,222123123,("小胡子",444),12341,"你好啊",["小明",123],)
    for a in tu :
    
     print(a)

    运算结果:

    222
    222123123
    ('小胡子', 444)
    12341
    你好啊
    ['小明', 123]
    
    Process finished with exit code 0

    3.转换

    转换成列表:

    tu = (222,"你好啊",["小明",123],)
    a = list(tu)
    
    print(a)

    运行结果

    [222, '你好啊', ['小明', 123]]
    
    Process finished with exit code 0

    转换成字符串:

    tu = (222,"你好啊",["小明",123],)
    b =" "
    for a in tu:
        b = b + str(a)
    
    print(b)

    运行结果:

     222你好啊['小明', 123]
    
    Process finished with exit code 0

    ps:元组基本功能和列表是一样的。

    4.元组一级元素无法增删改,但是里面的元素如果是列表是可以增删改的

    tu = (222,"你好啊",["小明",123],)
    tu[2][0]=132
    
    print(tu)

    运算结果:

    (222, '你好啊', [132, 123])
    
    Process finished with exit code 0

    5.元组的方法

    count   获取元素的个数

    index  获取元素的索引

    同列表的方法。

  • 相关阅读:
    django加载静态文件
    计算机网络-划分子网
    接口定义一个Kye.保证其安全性
    GridView中几个显示数据时! 数据停靠(靠左 or 居中)的问题!
    数据库SQL Case...when...then...end的用法!
    利用jQuery发送ajax异步请求
    利用索引进行数据查询优化(转载!)
    身份证的合法验证
    DataTable判断列是否为空!(实用)
    窗体美化,IrisSkin2.dll的使用!
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11103087.html
Copyright © 2020-2023  润新知