
上QQ阅读APP看书,第一时间看更新
2.2.2 元组元素的索引和输出
元组元素的索引规则和列表元素的索引规则完全一样,元组索引值也有两种建立方法:从左到右的方法和从右到左的方法。从左到右的方法也是从0开始逐渐增大,最左边的元素的索引值是0,然后依次增加1,右边最后一个元素的索引值最大,其索引值为len(tuple)-1;从右到左的方法也是索引值从-1开始逐渐减小,最右边的元素的索引值是-1,然后依次增加-1,左边最后一个元素的索引值最小,其索引值为-len(tuple)。
元组是不可变序列,不能通过索引修改元素的值,也不能用索引增加、删除元素,利用索引值可以输出元组中的数据。

用下面两种for循环的方法可以输出元组中所有的元素。

使用for循环和enumerate()函数,可以同时输出元组的索引和数据。

用元组的count(x)方法可以查询元组中出现x的次数,用index(x)方法可以输出第1次等于x的元素的索引,用index(x,[start],[end])方法可以输出从索引值start开始到索引值为end之间第1次等于x的元素的索引。如果元组的元素是列表,可以修改列表中的值。
