zoukankan      html  css  js  c++  java
  • 基础数据类型-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
  • 相关阅读:
    操作系统
    MarkDown语法实操
    mac 添加环境变量
    在django中建立mysql数据表时发生的低级错误
    models.Book.object.get()与models.Book.object.filter()区别
    django中数据库操作时distinct的用法
    ‘,’逗号并不是字符串的拼接方式
    django单表操作中update_or_create不能更新多于一个数据的信息
    在python中terminal中建立mysql数据库,无法再models.py 文件中建立数据库信息
    booleanfield()和booleanfield(default=True)在数据库的表中无法插入
  • 原文地址:https://www.cnblogs.com/z-joshua/p/6306705.html
Copyright © 2011-2022 走看看