zoukankan      html  css  js  c++  java
  • Python学习笔记--元组

    # 若元组只有一个元素,要在后面加上','
    def test_turple():
        # 空元组
        a = ()
        print(type(a))  # <class 'tuple'>
        # 不是元组
        b = ('hello')
        print(type(b))  # <class 'str'>
        c = (100)
        print(type(c))  # <class 'int'>
        # 一元组
        d = ('hello',)
        print(type(d))  # <class 'tuple'>
        e = (100,)
        print(type(e))  # <class 'tuple'>
    
    
    # 打包和解包
    def pack_turple():
        # 打包
        a = 1, 10, 100
        print(type(a), a)  # <class 'tuple'> (1, 10, 100)
        # 解包
        i, j, k = a
        print(i, j, k)  # 1 10 100
        # 若解包元素与元组内元素个数不同,则会报错
        # i,j = a # ValueError: too many values to unpack (expected 2)
        # 用星号表达式,有了星号表达式,我们就可以让一个变量接收多个值
        i, *j = a
        print(i)  # 1
        print(type(j), j)  # <class 'list'> [10, 100]
        # 打包解包对字符串,列表也适用
        a, b, *c = range(1, 10)
        print(a, b, c)  # 1 2 [3, 4, 5, 6, 7, 8, 9]
        a, b, c = [1, 10, 100]
        print(a, b, c)  # 1 10 100
        a, *b, c = 'hello'
        print(a, b, c)  # h ['e', 'l', 'l'] o
    
    
    # 可变参数的原理, 可变参数其实就是将多个参数打包成了一个元组
    # 两个**本质上是一个dict
    def test_param():
        def add(*args):
            print(type(args), args)
            total = 0
            for val in args:
                total += val
            return total
    
        print(add(1, 2))  # <class 'tuple'> (1, 2) 3
        print(add(1, 2, 3, 4, 5))  # <class 'tuple'> (1, 2, 3, 4, 5) 15
    
    
    # 交换两个数的值,python极为简单
    def exchange_two_nums(a, b):
        a, b = b, a
        print("a交换后是", a)
        print("b交换后是", b)
    
    
    # list和 turple区别
    # 元组是不可变类型,不可变类型更适合多线程环境,因为它降低了并发访问变量的同步化开销。关于这一点,我们会在后面讲解多线程的时候为大家详细论述。
    # 元组是不可变类型,通常不可变类型在创建时间和占用空间上面都优于对应的可变类型。
    # 列表和元组都是容器型的数据类型,即一个变量可以保存多个数据。列表是可变数据类型,元组是不可变数据类型,
    # 所以列表添加元素、删除元素、清空、排序等方法对于元组来说是不成立的。但是列表和元组都可以进行拼接、成员运算、索引和切片这些操作,
    # 就如同之前讲到的字符串类型一样,因为字符串就是字符按一定顺序构成的序列,在这一点上三者并没有什么区别。
    # 我们推荐大家使用列表的生成式语法来创建列表,它很好用,也是Python中非常有特色的语法。如 list1 = [x for x in range(1,10)]
    if __name__ == '__main__':
        # test_turple()
        # pack_turple()
        # test_param()
        exchange_two_nums(1, 3)
    

      

  • 相关阅读:
    树上启发式合并_训练总结+题目清单
    Wannafly Day2 E 阔力梯的树(树上启发式合并)
    profile(/etc/profile)和bash_profile的区别
    MacOS配置.bash_profile,重启终端后配置失效和MacOS .zshrc does not exist问题
    Markdown入门学习202004
    把-图片的链接-下载到本地(服务器);
    前端Vue- v-for 循环中删除 元素;
    关于谷歌浏览器(Chrome)前端JS方法调用方法,运行顺序出错问题;
    国外的api之ASANA-java开发-ASANAAPI(真难!)
    vue脚手架3.x完整版
  • 原文地址:https://www.cnblogs.com/jifeng0902/p/14692126.html
Copyright © 2011-2022 走看看