zoukankan      html  css  js  c++  java
  • day 12 元组的魔法

    元祖

    元组,其实是对列表的二次加工,元素不可被修改,不能被增加或者删除

    li = [11,22,33,44]    # 列表
    
    tu = (111,222,333,444,)  #元祖 

    # 元组,其实是对列表的二次加工,元素不可被修改,不能被增加或者删除 # 一般写元组的时候,推荐在最后加一个逗号

    1,索引

    tu = (111,222,333,444,)
    v = tu[0]
    # 索引
    print(v)

    结果:
    111

    2,切片

    tu = (111,222,333,444)
    s = tu[0:2]
    # 切片
    print(s)

    结果:
    (111, 222)

    3,for循环

    tu = (111,222,333,444)
    for item in tu:
    # for循环
    print(item)

    结果:

    111
    222
    333
    444

     4,count index

    获取指定元素在元组中出现的次数

    tu = (11,22,33,44)
    a = tu.count(22)
    b = tu.index(22)
    print(a,b)

     

     

    ######################################### 深灰魔法 #######################################

    1,书写格式

    1. 书写格式tu = (111,"alex",(11,22),[(33,44)],True,33,44,)一般写元组的时候,推荐在最后加入 元素不可被修改,不能被增加或者删除

     2,索引

    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    v = tu[0]
    print(v)
    结果:
    111

    3,切片

    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    v = tu[0:2]
    print(v)

    结果:
    (111, 'alex')

    4,可以被for循环,可迭代对象

    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    for item in tu:
        print(item)

    结果:

    111
    alex
    (11, 22)
    [(33, 44)]
    True
    33
    44



    5,转换

     

    字符串 转元祖

    s = "asdfasdf0"
    li = ["asdf","asdfasdf"]
    tu = ("asdf","asdf")
    
    v = tuple(s)  
    print(v)
    
    结果:
    ('a', 's', 'd', 'f', 'a', 's', 'd', 'f', '0')

    列表转元祖

    s = "asdfasdf0"
    li = ["asdf","asdfasdf"]
    tu = ("asdf","asdf")
    v = tuple(li)
    print(v)

    结果:
    ('asdf', 'asdfasdf')

    元祖转列表

    s = "asdfasdf0"
    li = ["asdf","asdfasdf"]
    tu = ("asdf","asdf")

    v = list(tu)
    print(v)

    结果:
    ['asdf', 'asdf']

    6,join拼接

    s = "asdfasdf0"
    li = ["asdf","asdfasdf"]
    tu = ("asdf","asdf")
    
    v = "_".join(tu)
    print(v)

    结果:
    asdf_asdf

    7,extend

    li = ["asdf","asdfasdf"]
    li.extend((11,22,33,))
    print(li)

    结果:
    ['asdf', 'asdfasdf', 11, 22, 33]

    8,元组的一级元素不可修改/删除/增加

       元组,有序。

    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    v = tu[3][0][0]
    print(v)

    结果:
    33
    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    v=tu[3]
    print(v)

    结果:
    [(33, 44)]
    tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    tu[3][0] = 567
    print(tu)

    结果:
    (111, 'alex', (11, 22), [567], True, 33, 44)
    # 6.元组的一级元素不可修改/删除/增加
    # tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
    # # 元组,有序。
  • 相关阅读:
    在SQL Server中保存和输出图片 (转)
    Oracle 和 IBMDB2 连接字符串
    DataSet中 新增 唯一键 外键
    ORACLE的数据类型
    window.event的属性
    学习资料下载
    防止 刷新 重做
    常用正则表达式 (转)
    JS 定时器 (setInterval 和 setTimeout 函数)
    ASP.NET 2.0 – 善用DataSourceMode属性 (转自章立民CnBlogs)
  • 原文地址:https://www.cnblogs.com/xiaomai-rhce/p/10085531.html
Copyright © 2011-2022 走看看