熟练掌握Python元组

发布时间:2022-03-22 09:49:49 人气:241 作者:多测师

  作为一种通用编程语言,Python已成为各学术和工业领域中最流行的语言之一。

  Python拥有强大的数据结构集合,例如int、 string、 list、 dict和 tuple——一个大小固定且不可变数据序列。

  在今天的文章里,多测师将带领大家回顾正确使用Python元组的最常用方法。

  1. 使用索引访问元组中的单个元素

  创建元组后,有时需要访问它的一些值。一种方法是使用基于0的索引对其进行访问。参见下方示例。值得注意的是,在Python中,使用负数以相反的顺序索引序列。例如,-1是序列中最后一个元素的索引。当然,如试图使用范围之外的索引访问元素,将看到IndexError(索引错误)。

  >>> tuple_index = (100,'text', False, {1: 'five', 2: True})>>> tuple_index[0]

  100>>> tuple_index[-1]

  {1: 'five', 2: True}>>> tuple_index[2]

  False>>> tuple_index[6]

  Traceback (most recent call last):

  File "", line 1,in

  IndexError: tuple index out of range

  2. 可变元素

  虽然一个元组不能作为一个对象整体改变,但如果单个元素本身是可变的,就可以对其进行更改。参见下方示例。具体来说,修改了tuple(元组)中的 list 和 dict.

  >>> mutable_elements =(1, [1, 2], {0: 'zero', 1: 'one'})>>> mutable_elements[1].append(3)

  >>> mutable_elements

  (1, [1, 2, 3], {0: 'zero', 1: 'one'})>>> mutable_elements[2][2] ='two'

  >>> mutable_elements

  (1, [1, 2, 3], {0: 'zero', 1: 'one', 2: 'two'})

  3. 高级元组拆包

  有时拆包一个元组,并不需要访问所有的单个元素。对于那些不重要的元素,可以用下划线(_)表示。另一种高级的tuple (元组)拆包技术是,使用星号(*)表示tuple (元组)中的元素序列。_和*用法也可以组合使用。

  >>> advanced_unpacking0= (1, 2, 3)

  >>> a, _, c = advanced_unpacking0

  >>> a

  1

  >>> c

  3>>> advanced_unpacking1 = (1, 2, 3, 4, 5, 11, 12, 13, 14, 15)

  >>> a, *middle, c = advanced_unpacking1

  >>> middle

  [2, 3, 4, 5, 11, 12, 13, 14]

  >>> _, *tail = advanced_unpacking1

  >>> tail

  [2, 3, 4, 5, 11, 12, 13, 14, 15]

  >>> head, *_ = advanced_unpacking1

  >>> head

  1

熟练掌握Python元组

  4. 使用值序列创建元组

  创建元组时,需使用逗号分隔值序列。括号是可选的,尤其在声明表达式不直接的情况下,使用括号可以提高可读性。

  >>> tuple0 = 1, 4, 5

  >>> print(tuple0)

  (1, 4, 5)>>> tuple1 = (1, 2, 'three')

  >>> print(tuple1)

  (1, 2, 'three')>>> tuple2 = (4, 7, ('a', 'b'), lambda x: x+1)

  >>> print(tuple2)

  (4, 7, ('a', 'b'), at 0x106e98830>)>>>tuple3 = ()

  >>> print(tuple3)

  ()>>> tuple4 = 'one',

  >>> print(tuple4)

  ('one',)

  特殊的情况是:使用一对括号创建一个空tuple(元组);在唯一值后使用逗号创建单值tuple(元组)。

  5. 计算元组中元素的数量

  由于tuple(元组)是一个序列,所以可使用len()函数计算所有元素总数。另一个函数 count()也很方便,可用做计算调用时指定的某个值的个数。参见下方示例。

  >>> tuple_len = (1, 3,'one', 'three', 'five')

  >>> len(tuple_len)

  5>>> tuple_count = (1, 1, 2, 2, 2, 2, 3, 3, 3)

  >>> tuple_count.count(2)

  4

  >>> tuple_count.count(3)

  3

  6. 使用tuple()函数创建元组

  可使用内置 tuple()方法创建元组,该方法将 iterable (迭代)作为唯一参数。生成的tuple (元组)将是 iterable 的迭代项序列。如下示例中,元组分别从str、dict和 list生成。

  >>> tupletuple5 =tuple(['a', 'b'])

  >>> print(tuple5)

  ('a', 'b')>>> tupletuple6 = tuple('tuple')

  >>> print(tuple6)

  ('t', 'u', 'p', 'l', 'e')>>> tupletuple7 = tuple({'a': 1, True: 4})

  >>> print(tuple7)

  ('a', True)>>> tupletuple8 = tuple((1, 'two', [1, 2]))

  >>> print(tuple8)

  (1, 'two', [1, 2])

  7. 使用拆包方法访问元组的单个元素

  使用元组可能经常听到的另一个概念是tuple(元组)拆包,它允许访问单个元素。参见下方示例。

  >>> tuple_unpacking =(1, 'two', [3, 3, 3], {'four': 4})

  >>> a, b, c, d = tuple_unpacking>>> a

  1

  >>> b

  'two'

  >>> c

  [3, 3, 3]

  >>> d

  {'four': 4}

  8. for循环中的元组

  时常需要在for循环中使用元组。由于元组是可迭代的,所以可直接在for循环中使用,该循环将迭代元组的单个元素。或者,如果想应用计数器,可使用元组内置的 enumerate() 方法。参见下方示例。

  >>> tuple_for_loop =('one', 'two', 'three')

  >>> for i in tuple_for_loop:

  ... print(i)

  ...

  one

  two

  three>>> for (i, item) in enumerate(tuple_for_loop, start=1):

  ... print(str(i) + ': is ' + item)

  ...

  1: is one

  2: is two

  3: is three

  9. 元组的不可变性

  正如本文开头提到的,元组是一个不可变值序列。因此,不能改变单个元素的值。

  >>> immut_tuple = (3,5, 7)

  >>> immut_tuple[0] = 1

  Traceback (most recent call last):

  File "", line 1,in

  TypeError: 'tuple' object does not support item assignment

  10. 元组连接

  可使用加号(+)运算符连接多个元组,来创建一个新元组。或者,如果想通过多次连接同一元组来创建一个新的元组,可使用乘法(*)运算符。

  >>> concat_tuple0 = (1,2) + ('three', 4) + ('five', 6)

  >>> concat_tuple0

  (1, 2, 'three', 4, 'five', 6)>>> concat_tuple1 = ('odd', 'event') * 4

  >>> concat_tuple1

  ('odd', 'event', 'odd', 'event', 'odd', 'event', 'odd', 'event')

  元组是笔者在Python编程中最喜欢使用的数据结构之一,因其便于构造和访问单个元素。当然,请记住元组是不可变的,并且没有过多的方法,这可能限制其更广泛的使用,这种情况下,可以考虑使用list 或dict。

  以上内容为大家介绍了熟练掌握Python元组,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/

返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线