想要熟练掌握Python元组?你需要了解这10件应知事项

全文共3618字,预计学习时长11分钟

来源:Pexels

人生苦短,Python是岸。

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

此前,IEEESpectrum 发布的第五届年度编程语言交互排行榜中,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 "<stdin>", line 1,in <module>
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

4.使用值序列创建元组

来源:Pexels

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

>>> 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'), <function <lambda> 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生成。

>>> tuple5 =tuple(['a', 'b'])
>>> print(tuple5)
('a', 'b')>>> tuple6 = tuple('tuple')
>>> print(tuple6)
('t', 'u', 'p', 'l', 'e')>>> tuple7 = tuple({'a': 1, True: 4})
>>> print(tuple7)
('a', True)>>> tuple8 = 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循环中的元组

来源:Pexels

时常需要在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 "<stdin>", line 1,in <module>
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')

来源:Pexels

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

留言 点赞 关注

我们一起分享AI学习与发展的干货
欢迎关注全平台AI垂类自媒体 “读芯术”

(添加小编微信:dxsxbb,加入读者圈,一起讨论最新鲜的人工智能科技哦~)

发布了1031 篇原创文章 · 获赞 3012 · 访问量 68万+

猜你喜欢

转载自blog.csdn.net/duxinshuxiaobian/article/details/105514104
今日推荐