赞
踩
Tuple(元组)是python的基本序列三种类型之一(另外两种是List, Range),是“笨方法“学python3中没有讲到的数据类型,因此专门查了下官方资料,中可以查找到对Tuple解释,它是一种不可改变的序列,即序列值已经序列顺序在创建初始化时就已经固定好,其内容不可改变,通常是用于收据异构数据结果防止被改变(在异构计算中比较有优势),还可以在一个class中定义一个元素用于异构计算,由此看来该结构和AI有很大的关联性(在此建议,学语言多看官方文档能收获很多,毕竟原文才是最好的理解,每个人都有自己的理解角度,有的时候会有较大偏差,“”笨方法“学python3中的很多知识点都需要自己去扩充)。官方文档原文解释如下:
由上述特性可知,与list最大的不同就是,元组内容不可改,而list可以修改,我个人理解为 list的常量,可以为list的一种特殊形式,但不支持list很多操作。
Tuple的表示方法和list不一样,list是由【】表示,而Tuple是用()表示,元素之间同样使用,号表示,其创建方法官方解释只给出了四种
1: 创建一个空的Tuple,之间使用()即可
- tup1=()
- print(tup1)
运行结果:
2:创建只有一个元素,为了避免歧义,需要在元素后面添加一个逗号(a,)
- company=("huawei",)
- print(company)
运行结果:
不加逗号,会把括号认为运算符,其运行结果如下:
3:创建有多个元素的tuple:
- companys=("huawei", "Google","Ali","Baidu")
- print(companys)
运行结果如下:
4:利用其build-in函数,使用迭代器创建一个tuple
当迭代器本身就是一个tuple,新建的tuple就是完全复制一个新的tuple,值和序列完全一样:
- companys=("huawei", "Google","Ali","Baidu")
- companys1=tuple(companys)
- print(companys1)
运行结果:
当参数为一个字符串时,其tuple 按照list进行转换,将每个字符转成一个元素,例子如下:
- companys2=tuple('huawei')
- print(companys2)
运算结果如下:
当参数为一个list时,将按照顺序和值转换成一个tuple,例子如下:
- listcompany=["Facebook","Tecent","ARM","JingDong"]
- companys3=tuple(listcompany)
- print(companys3)
运行结果如下:
对元组访问和list访问方式一样的,都是采用index方式,例子如下:
- companys=("huawei", "Google","Ali","Baidu")
- print(companys[2])
- print(companys[1])
运行结果如下:
元组不运行删除某个元素值,只能使用del删除整个元组,不在举例子
除了上述操作外,元组同样支持序列的common操作, common操作如下:
Operation | Result |
x in s | True if an item of s is equal to x, else False |
x not in s | False if an item of s is equal to x, else True |
s + t | the concatenation of s and t |
s * n or n * s | equivalent to adding s to itself n times |
s[i] | ith item of s, origin 0 |
s[i:j] | slice of s from i to j |
s[i:j:k] | slice of s from i to j with step k |
len(s) | length of s |
min(s) | smallest item of s |
max(s) | largest item of s |
s.index(x[, i[, j]]) | index of the first occurrence of x in s (at or after index i and before index j) |
s.count(x) | total number of occurrences of x in s |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。