Python TUPLE – 打包、解包、比较、切片、删除、键

⚡ 智能摘要

Python Tuple is an ordered, immutable collection of values written in parentheses. The examples below cover tuple packing and unpacking, comparing tuples, using tuples as dictionary keys, deleting, slicing, and the advantages of tuples over lists.

  • 📦 定义: A tuple is an ordered, immutable collection created with parentheses.
  • 🔁 Packing/Unpacking: Group values into a tuple, then extract them back into variables.
  • 比较: Tuples are compared element by element from left to right.
  • ???? Dictionary Keys: Because tuples are hashable, they can act as composite dictionary keys.
  • ✂️ 切片: Fetch sub-elements from a tuple using slice notation.
  • 🚀 优点: Tuples are faster and write-protected compared to lists.

Python 元组

什么是元组匹配 Python?

元组匹配 Python 是一种分组方法ping 通过匹配元组中的第二个元素来创建元组。这可以通过在 Python 编程中使用字典来实现,方法是检查每个元组中的第二个元素。但是,我们也可以通过从现有元组中提取部分元素来创建新元组。

元组语法

Tup = ('Jan','feb','march')

要写一个空元组,你需要写两个不包含任何内容的括号 -

tup1 = ();

对于单个值的元组,即使只有一个值,也需要包含逗号。此外,末尾还需要写分号,如下所示。

Tup1 = (50,);

元组索引从 0 开始,并且可以进行连接、切片等等。

元组赋值

Python 具有元组分配功能,可让您一次分配多个变量。在这里,我们已将姓名、姓氏、出生年份等个人信息分配给元组 1,并将其中的值分配给另一个元组 2,例如数字 (1,2,3,….,7)。

例如,

(名字、姓氏、出生年份、最喜欢的电影和年份、职业、出生地) = 罗伯特

这是代码,

tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print(tup1[0])
print(tup2[1:4])
  • 元组 1 包含 Robert 的信息列表
  • 元组 2 包含数字列表
  • 我们将元组中 [0] 的值称为元组,将元组 2 中的值称为 1 到 4 之间的值
  • 运行代码-它为第一个元组给出名称 Robert,而为第二个元组给出数字(2,3、4 和 XNUMX)

打包和拆包

在打包过程中,我们将值放入一个新的元组中;而在解包过程中,我们则……trac将这些值转换回变量。

x = ("Guru99", 20, "Education")    # tuple packing
(company, emp, profile) = x    # tuple unpacking
print(company)
print(emp)
print(profile)

比较元组

比较运算符 Python 可以处理元组。

比较从每个元组的第一个元素开始。如果它们与 =、< 或 > 不匹配,则继续比较第二个元素,依此类推。

首先比较每个元组的第一个元素

让我们通过一个例子来研究一下

#情况1

a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")

#情况2

a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")

#情况3

a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
else: print("b is bigger")

情况1: 比较从每个元组的第一个元素开始。在本例中,5>1,因此输出 a 较大

案例2: 比较从每个元组的第一个元素开始。在本例中,5>5,结果不确定。因此,它继续比较下一个元素。6>4,因此输出 a 较大

案例3: 比较从每个元组的第一个元素开始。在本例中,5>6 为假。因此它进入 else 块并打印“b 更大”。

使用元组作为字典中的键

由于元组是可哈希的,而列表不是,所以如果我们需要创建一个用于字典中的复合键,我们必须使用元组作为键。

例如::如果我们需要创建一个电话簿,映射名字、姓氏、电话号码对等,我们就会遇到复合键。假设我们已经将变量声明为姓氏和名字,我们可以编写一个字典赋值语句,如下所示:

directory[last,first] = number

括号内的表达式是一个元组。我们可以在 for 循环中使用元组赋值来浏览这个字典。

for last, first in directory:
print first, last, directory[last, first]

此循环浏览目录中的键,这些键是元组。它将每个元组的元素分配到最后和最前面,然后打印姓名和相应的电话号码。

元组和字典

Dictionary 可以通过调用 items 返回元组列表,其中每个元组都是一个键值对。

a = {'x':100, 'y':200}
b = list(a.items())
print(b)

删除元组

元组是不可变的,不能被删除。您不能从元组中删除或移除项目。但可以使用关键字

del

元组的切片

要从元组或列表中获取特定的子元素集,我们使用这个称为切片的独特函数。切片不仅适用于元组,也适用于数组和列表。

x = ("a", "b","c", "d", "e")
print(x[2:4])

该代码的输出将是('c','d')。

这里是 Python 2 Code 以上所有示例

tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print  tup1[0]
print  tup2[1:4]

#Packing and Unpacking
x = ("Guru99", 20, "Education")    # tuple packing
(company, emp, profile) = x    # tuple unpacking
print company
print emp
print profile

#Comparing tuples
#case 1
a=(5,6)
b=(1,4)
if (a>b):print "a is bigger"
else: print "b is bigger"

#case 2
a=(5,6)
b=(5,4)
if (a>b):print "a is bigger"
else: print "b is bigger"

#case 3
a=(5,6)
b=(6,4)
if (a>b):print "a is bigger"
else: print "b is bigger"

#Tuples and dictionary
a = {'x':100, 'y':200}
b = a.items()
print b 

#Slicing of Tuple
x = ("a", "b","c", "d", "e")
print x[2:4]

带有 Tuple 的内置函数

为了执行不同的任务,tuple 允许您使用许多内置函数,如 all()、any()、enumerate()、max()、min()、sorted()、len()、tuple() 等。

元组相对于列表的优势

  • 通过元组进行迭代比通过列表进行迭代更快,因为元组是不可变的。
  • 由不可变元素组成的元组可以用作字典的键,而列表则无法做到这一点
  • 如果你有不可变的数据,将其实现为元组将保证它保持写保护

常见问题

A tuple is immutable and written with parentheses, while a list is mutable and written with square brackets. Tuples are faster and can be dictionary keys; lists are better when you need to add, remove, or change items.

No. Tuples are immutable, so you cannot change, add, or remove their elements after creation. If you need a modified version, create a new tuple, or convert the tuple to a list, change it, and convert it back.

Add a trailing comma after the value, such as t = (50,). Without the comma, Python treats the parentheses as a normal grouping and creates an integer, not a tuple. The comma is what makes it a single-element tuple.

Use tuple() to turn a list into a tuple, for example tuple([1, 2, 3]). To go the other way, use list() on the tuple. Conversion is handy when you must temporarily modify data that is otherwise fixed.

Yes. A tuple can hold mixed types such as strings, integers, and floats, and it can contain other tuples or lists. Nested tuples let you model rows, coordinates, or records where each position has a clear meaning.

A named tuple, from the collections module, gives each position a name so you can read fields by label instead of index. It keeps tuple immutability and speed while making code far more readable, like a lightweight class.

Tuples store fixed, ordered data such as array shapes, coordinates, and dataset records. Libraries like NumPy and pandas use tuples for shapes and index keys. Their immutability keeps machine learning data safe to pass around without accidental changes.

Yes. These AI assistants can generate tuple packing, unpacking, and slicing code from a plain-English prompt, then explain each line. They also suggest when a tuple fits better than a list. Always review and test generated code before using it.

总结一下这篇文章: