python-元组方法(tulpe)知识

发布时间:2019-04-09 21:38:35编辑:auto阅读(1645)

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # __author__:anxu.qi
    # Date:2018/11/21

    # 元组的特性,元组的元素不可被修改,元素的内部可以修改

    ################################## 元组 ###############################
    # 元组和列表几乎是一样的,也是一组数,只不过他一旦创建,便不能再修改,所以又叫只读列表。
    # 列表是可以进行修改的,元组是不能修改的

    name_list = ("beijing","shanghai","jinan","shandong")
    ## 索引
    print(name_list[0])
    # beijing

    ## len
    print(len(name_list))
    # 4

    ## 切片
    print(name_list[0:2])
    # ('beijing', 'shanghai')

    ## for 循环
    for i in name_list:
    print(i)
    """
    beijing
    shanghai
    jinan
    shandong
    """
    ################################## 删除元组元素报错 ###############################
    name_list = ("beijing","shanghai","jinan","shandong")
    # del name_list[0]
    # TypeError: 'tuple' object doesn't support item deletion (说的是“tuple”对象不支持删除项)


    ################################## count 统计个数 ###############################
    # def count(self, value):
    # 统计元素个数
    name_list = ("beijing","shanghai","jinan","shandong","beijing")
    print(name_list.count("beijing"))
    # 2


    ################################## index 获取索引 ###############################
    # def index(self, value, start=None, stop=None):
    # 获取指定元素的下标位置
    name_list = ("beijing","shandong","shanghai","jinan","shandong")
    print(name_list.index('shandong')) # 获取的下标只能从左往右
    # 1


    ################################## 元组 ###############################


关键字