zoukankan      html  css  js  c++  java
  • python元组

    Python基础数据类型之元组

    一、什么是元组

    元组是Python的基础数据类型之一,它与列表非常相似,最主要的区别在于列表是可变的,而元组是不可变的,即元组创建以后不可修改。

    二、如何创建一个元组及其注意事项

    方法1:用小括号将数据包裹起来,之间用逗号隔开就形成了元组。但是要注意的是当数据只有一个时,在数据后面一定要加上一个逗号,这样Python解释器才能识别这是一个元组,否则Python将把它当做其他数据来处理。

    >>> tuple1 = (1,2,3,4)
    >>> tuple1
    (1, 2, 3, 4)
    >>> type(tuple1)
    <class 'tuple'>
    >>> tuple2 = (1,)       # 加了逗号为元组
    >>> type(tuple2)
    <class 'tuple'>
    >>> tuple3 = (1)
    >>> type(tuple3)        #没有加逗号,Python解释器当做其他数据处理
    <class 'int'>
    >>> tuple4 = 1,2,3,4  #即使没有小括号,Python解释器依然会识别为元组
    >>> tuple4
    (1, 2, 3, 4)
    >>> type(tuple4)
    <class 'tuple'>
    >>>

    方法2:利用内置函数tuple(iterable)来将一个可迭代序列转换成元组。

    >>> list1 = [1,2,3,4]
    >>> tuple1 = tuple(list1)
    >>> tuple1
    (1, 2, 3, 4)
    >>> type(tuple1)
    <class 'tuple'>
    >>> tuple2 = tuple('Keys')
    >>> tuple2
    ('K', 'e', 'y', 's')
    >>>

    三、元组的方法

    元组即不可变列表,由于它是不可变的,所以它的方法也少的多,只有两个方法:count()和index()。

    1.统计某个元素在元组中的个数(count)

    >>> tuple1 = (1,1,2,3,3,3)
    >>> tuple1.count(1)
    2
    >>> tuple1.count(3)
    3
    >>>

    2.返回某个元素在元组中的索引值(index)

    >>> tuple1 = (1,1,2,3,3,3)
    >>> tuple1.count(1)
    2
    >>> tuple1.count(3)
    3
    >>> tuple1 = (1,2,3,'Keys')
    >>> tuple1.index(2)
    1
    >>> tuple1.index('Keys')
    3
    >>>
  • 相关阅读:
    HDU 1076 An Easy Task
    299 Train Swapping
    HDU 1092 A+B for InputOutput Practice (IV)
    HDU 1093 A+B for InputOutput Practice (V)
    HDU 1049 Climbing Worm
    HDU 1032 The 3n + 1 problem
    HDU 1089 A+B for InputOutput Practice (I)
    HDU 1091 A+B for InputOutput Practice (III)
    Vimperator
    成为高效程序员的搜索技巧[转自月光博客]
  • 原文地址:https://www.cnblogs.com/Keys819/p/9287406.html
Copyright © 2011-2022 走看看