geekdoc-python-zh/docs/overiq/163.md

7.3 KiB

Python 中的元组

原文:https://overiq.com/python-101/tuples-in-python/

最后更新于 2020 年 9 月 22 日


元组

元组是像列表一样工作的序列,唯一的区别是它们是不可变的,这意味着一旦它被创建,我们就不能添加、移除或修改它的元素。与列表相比,这也使它们超级高效。元组用于存储不变的项目列表。

创建元组

元组可以通过在一对括号内列出用逗号(,)分隔的元素来创建,即()。以下是一些例子:

>>>
>>> t = ("alpha", "delta", "omega")
>>>
>>> t
('alpha', 'delta', 'omega')
>>>
>>> type(t)
<class 'tuple'>
>>>

现在试试

下面是我们如何创建一个空元组:

>>>
>>> et = ()    # an empty tuple
>>> et
()
>>>
>>> type(et)
<class 'tuple'>
>>>

现在试试

我们也可以使用构造函数即tuple(),它接受任何类型的序列或可迭代对象。

>>>
>>> t1 = tuple("abcd")         # tuple from string
>>>
>>> t1
('a', 'b', 'c', 'd')
>>>
>>>
>>> t2 = tuple(range(1, 10))   # tuple from range
>>>
>>> t2
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>>
>>>
>>> t3 = tuple([1,2,3,4])      # tuple from list
>>> t3
(1, 2, 3, 4)
>>>

现在试试

列表理解也可以用来创建元组。

>>>
>>> tlc = tuple([x * 2 for x in range(1, 10)])
>>> tlc
(2, 4, 6, 8, 10, 12, 14, 16, 18)
>>>

现在试试

要创建一个只有一个元素的元组,必须在值后键入尾随逗号,否则它就不是元组。例如:

>>>
>>> t1 = (1,)   # this is a tuple
>>> type(t1)
<class 'tuple'>
>>>
>>>
>>> t2 = (1)   # this is not 
>>> type(t2)
<class 'int'>
>>>

现在试试

使用括号括住元组的元素是可选的。这意味着我们也可以创建这样的元组:

>>>
>>> t1 = "alpha", "delta", "omega"    # t1 is a tuple of three elements
>>> t1
('alpha', 'delta', 'omega')
>>> type(t1)
<class 'tuple'>
>>>
>>>
>>> t2 = 1, 'one', 2, 'two', 3, 'three'  # t2 is a tuple of six elements
>>> t2
(1, 'one', 2, 'two', 3, 'three')
>>> type(t2)
<class 'tuple'>
>>>

现在试试

请注意,虽然我们在创建元组时没有使用括号,但是 Python 在打印元组时使用了它们。

和以前一样,要创建一个元组,需要在值后有一个元素尾随逗号(,)。

>>>
>>> t1 = 1,
>>> t1
(1,)
>>> type(t1)
<class 'tuple'>
>>>
>>>
>>> t2 = 1
>>> t2
1
>>> type(t2)
<class 'int'>
>>>

现在试试

我们将在创建元组时显式使用括号。然而,另一种形式也有它的用途,最明显的是当从函数返回多个值时。

元组解包

元组允许您一次为多个变量赋值。例如:

>>>
>>> first, second, third = ("alpha", "beta", "gamma")
>>>
>>> first
'alpha'
>>> second
'beta'
>>> third
'gamma'
>>>

现在试试

这就是所谓的元组解包。变量的数量(在左边)和元组中元素的数量(在右边)必须匹配,否则你会得到一个错误。

>>>
>>> first, second, third, fourth = ("alpha", "beta", "gamma")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>>
>>>
>>> first, second, third = ("alpha", "beta", "gamma", "phi")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)
>>>

现在试试

因为括号是可选的,所以上面的代码也可以写成:

>>>
>>> first, second, third = "alpha", "beta", "gamma"
>>>
>>> first
'alpha'
>>> second
'beta'
>>> third
'gamma'
>>>

现在试试

回想一下,我们已经在 Python 中的数据类型和变量一课中,在标题同时赋值下了解到这一点。好吧,现在你知道在幕后我们在不知不觉中使用元组了!

元组的运算

元组本质上是一个不可变的列表。因此,可以对列表执行的大多数操作对元组也是有效的。以下是此类操作的一些示例:

  • 使用[]运算符访问单个元素或元素切片。
  • max()min()sum()这样的内置函数对元组有效。
  • 会员操作员innot in
  • 比较元组的比较运算符。
  • +*操作员。
  • for 循环遍历元素。

等等。

每当您面临一个操作对元组是否有效的两难问题时,只需在 Python Shell 中尝试一下。

元组不支持的唯一操作类型是修改列表本身的操作。因此append()insert()remove()reverse()sort()等方法不适用于元组。

下面的程序演示了可以对元组执行的一些常见操作。

蟒蛇 101/第-20 章/operations_on_tuple.py

tuple_a = ("alpha", "beta", "gamma")
print("tuple_a:", tuple_a)
print("Length of tuple_a:", len(tuple_a))  # len() function on tuple

tuple_b = tuple(range(1,20, 2)) # i.e tuple_b = (1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
print("\ntuple_b:", tuple_b)
print("Highest value in tuple_b:", max(tuple_b))   # max() function on tuple
print("Lowest value in tuple_b:",min(tuple_b))   # min() function on tuple
print("Sum of elements in tuple_b:",sum(tuple_b))   # sum() function on tuple

print("\nIndex operator ([]) and Slicing operator ([:]) : ")
print("tuple_a[1]:", tuple_a[1])
print("tuple_b[len(tuple_b)-1]:", tuple_b[len(tuple_b)-1])
print("tuple_a[1:]:", tuple_a[1:])

print("\nMembership operators with tuples: ")
print("'kappa' in tuple_a: ",'kappa' in tuple_a)
print("'kappa' not in tuple_b: ",'kappa' not in tuple_b)

print("\nIterating though elements using for loop")
print("tuple_a: ", end="")
for i in tuple_a:
    print(i, end=" ")

print("\ntuple_b: ", end="")
for i in tuple_b:
    print(i, end=" ")

print("\n\nComparing tuples: ")
print("tuple_a == tuple_b:", tuple_a == tuple_b)
print("tuple_a != tuple_b:", tuple_a != tuple_b)

print("\nMultiplication and addition operators on tuples: ")
print("tuple * 2:", tuple_a * 2)
print("tuple_b + (10000, 20000): ", tuple_b + (10000, 20000))

现在试试

输出:

tuple_a: ('alpha', 'beta', 'gamma')
Length of tuple_a: 3

tuple_b: (1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
Highest value in tuple_b: 19
Lowest value in tuple_b: 1
Sum of elements in tuple_b: 100

Index operator ([]) and Slicing operator ([:]) : 
tuple_a[1]: beta
tuple_b[len(tuple_b)-1]: 19
tuple_a[1:]: ('beta', 'gamma')

Membership operators with tuples: 
'kappa' in tuple_a:  False
'kappa' not in tuple_b:  True

Iterating though elements using for loop
tuple_a: alpha beta gamma 
tuple_b: 1 3 5 7 9 11 13 15 17 19 

Comparing tuples: 
tuple_a == tuple_b: False
tuple_a != tuple_b: True

Multiplication and addition operators on tuples: 
tuple * 2: ('alpha', 'beta', 'gamma', 'alpha', 'beta', 'gamma')
tuple_b + (10000, 20000):  (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 10000, 20000)