• 基础数据类型-tuple


    Python中,元组tuple与list类似,不同之处在于tuple的元素不能修改,tuple使用(),list使用[],

    (1)元组的创建使用(),需要注意的是创建包含一个元素的元组:

    1 tuple_number = ()
    2 tuple_number = (1, ) #创建一个元素的元组,在元素后加逗号
    3 print("type of (1) is:", type((1))) #(1)的类型是整形
    4 
    5 type of (1) is: <class 'int'>

    (2)元组的索引,切片,检查成员,加,乘

     1 #索引
     2 tuple_number = (1, 2, 3, 4, 5)
     3 print("tuple_number[2]:", tuple_number[2])
     4 #切片
     5 print("tuple_number[1:4]:", tuple_number[1:4])#index = 4的元素不包含
     6 #检查成员
     7 if 6 in tuple_number:
     8     print("6 is in tuple_number")
     9 else:
    10     print("6 is not in tuple_number")
    11 #
    12 tuple_name = ('John', 'Paul')
    13 print("tuple_number plus tuple_name:", tuple_number + tuple_name)
    14 #
    15 print("tuple_number * 2:", tuple_number * 2)
    Code
    1 tuple_number[2]: 3
    2 tuple_number[1:4]: (2, 3, 4)
    3 6 is not in tuple_number
    4 tuple_number plus tuple_name: (1, 2, 3, 4, 5, 'John', 'Paul')
    5 tuple_number * 2: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
    Result

    (3)tuple的遍历和list一样: for number in tuple_number:print(number) 

    (4)与list一样,tuple也有函数:len(),max(),min(),tuple()

    (5)由于tuple的元素不允许修改,tuple的内置方法只有count(),index()

    1 #方法
    2 tuple_number = (1, 1, 2, 2, 2, 3, 3, 3, 3)
    3 print("count of 2 in tuple_number:", tuple_number.count(2)) #元素出现的次数
    4 print("index of first 3:", tuple_number.index(3)) #元素第一次出现的位置
    Code
    1 count 2 in tuple_number: 3
    2 index of first 3: 5
    Result

    (6)最后看看tuple类的定义:

     1 class tuple(object):
     2     """
     3     tuple() -> empty tuple
     4     tuple(iterable) -> tuple initialized from iterable's items
     5     
     6     If the argument is a tuple, the return value is the same object.
     7     """
     8     def count(self, value): # real signature unknown; restored from __doc__
     9         """ T.count(value) -> integer -- return number of occurrences of value """
    10         return 0
    11 
    12     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
    13         """
    14         T.index(value, [start, [stop]]) -> integer -- return first index of value.
    15         Raises ValueError if the value is not present.
    16         """
    17         return 0
    Class Tuple
  • 相关阅读:
    如何利用docker制作自己的镜像
    python 获取当前运行的 class 和 方法的名字
    UnitTest-case参数化
    值得推崇的一种图书出版的方式----开源图书
    Django中对数据查询、删除、修改
    wireshark网络实战分析二
    wireshark网络抓包分析
    邮件传输协议实战抓包分析
    socket服务端给客户端发送数据第一次不成功,第二次成功
    转载:Wireshark抓包详解
  • 原文地址:https://www.cnblogs.com/z-joshua/p/6306705.html
Copyright © 2020-2023  润新知