Python 简明教程

Python - Immutable Data Structures

Python Immutable data structures 是数据结构,一旦创建,便无法更改。这意味着任何修改数据结构的尝试都会导致创建一个新实例,而不是更改原始实例。不可变数据结构有助于确保数据在程序执行期间保持不变,这有助于防止出现错误并使代码更易于理解和维护。

The Python Immutable data structures are the data structures that once created, cannot be changed. This means that any attempt to modify the data structure will result in a new instance being created rather than altering the original. Immutable data structures are useful for ensuring that data remains constant throughout the execution of a program which can help prevent bugs and make code easier to understand and maintain.

在深入探讨此主题之前,让我们快速回顾一下 what is datastructure? 数据结构是用于组织、处理、检索和存储数据的专门格式。它们定义了数据在内存中的排列方式以及如何高效地执行诸如访问、插入、删除和更新之类的操作。

Before proceeding deep into this topic let’s have a quick recall of what is datastructure? The Data structures are specialized formats for organizing, processing, retrieving and storing data. They define how data is arranged in memory and how operations such as accessing, inserting, deleting and updating can be performed efficiently.

Different Immutable Data Structures in Python

不可变数据结构在 Python 中对于其稳定性、线程安全性以及易用性至关重要。以下是 Python 中的不同不可变数据结构 -

Immutable data structures are essential in Python for their stability, thread-safety and ease of use. Here are the different immutable data structures in Python −

  1. Tuples: These are the ordered collections of items that cannot be changed after their creation. They can contain mixed data types and are useful for representing fixed collections of related items.

  2. Strings: These Data structures are sequences of characters and are immutable. Any operation that modifies a string will create a new string.

  3. Frozensets: These are immutable versions of sets. Unlike regular sets, frozensets do not allow modification after creation.

  4. Named Tuples: These are a subclass of tuples with named fields which provide more readable and self-documenting code. They are immutable like regular tuples.

现在,让我们详细了解每种不可变数据结构。

Now, let’s proceed about the each Immutable data structures in detail.

Tuples

Python 中的元组是不可变的元素序列,这意味着一旦创建,便无法修改它们。它们使用括号“(”和“)”定义,并且可以保存数字、字符串甚至其他元组之类的项目集合。

Tuples in Python are immutable sequences of elements which means once created, they cannot be modified. They are defined using parentheses '()' and can hold a collection of items such as numbers, strings and even other tuples.

Creating Tuples

元组使用括号“(”和“)”创建,元素之间用逗号“,”分隔。即使只有一个元素的元组也需要尾随逗号,以将其与分组表达式区分开。

Tuples are created using parentheses '()' and elements separated by commas ','. Even tuples with a single element require a trailing comma to distinguish them from grouped expressions.

以下是通过为变量分配括号“(”和“)”来创建元组的示例 -

Following is the example of creating a tuple by assigning parentheses '()' to a variable −

empty_tuple = ()
single_element_tuple = (5,)  # Note the comma after the single element
print("Single element tuple:", single_element_tuple)
multi_element_tuple = (1, 2, 'Tutorialspoint', 3.14)
print("Multi elements tuple:", multi_element_tuple)
nested_tuple = (1, (2, 3), 'Learning')
print("Nested tuple:", nested_tuple)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Single element tuple: (5,)
Multi elements tuple: (1, 2, 'Tutorialspoint', 3.14)
Nested tuple: (1, (2, 3), 'Learning')

Understanding Tuple Immutability in Python

这里我们要了解 Python 中元组的不可变性。以下示例 −

Here we are going understand the immutability of the tuples in python. Below is the example −

# Define a tuple
my_tuple = (1, 2, 3, 'hello')
# Attempt to modify an element (which is not possible with tuples)
# This will raise a TypeError
try:
   my_tuple[0] = 10
except TypeError as e:
   print(f"Error: {e}")
# Even trying to append or extend a tuple will result in an error
try:
   my_tuple.append(4)
except AttributeError as e:
   print(f"Error: {e}")
# Trying to reassign the entire tuple to a new value is also not allowed
try:
   my_tuple = (4, 5, 6)
except TypeError as e:
   print(f"Error: {e}")
print("Original tuple:", my_tuple)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Error: 'tuple' object does not support item assignment
Error: 'tuple' object has no attribute 'append'
Original tuple: (4, 5, 6)

Strings

Python 中的字符串是一系列字符,用于表示和操作文本数据。它们被单引号 ' 或双引号 " 括起来,也可以使用三引号 """ 表示多行字符串。

Strings in Python are sequences of characters which are used to represent and manipulate textual data. They are enclosed within either single quotes ' or double quotes " with the option to use triple quotes """ for multi-line strings.

关键特征包括不可变性,这意味着一旦创建,这些字符串就不能被更改,有序索引,其中字符按位置访问,支持各种操作,例如连接、切片和迭代。

Key characteristics include immutability which means once created those strings cannot be changed, ordered indexing where characters are accessed by position and support for various operations such as concatenation, slicing and iteration.

字符串在 Python 中对于任务至关重要,例如文本处理、输入/输出操作和应用程序中的数据表示,提供了一个通用的工具集,带有用于高效操作和格式化文本信息的内置方法。

Strings are fundamental in Python for tasks such as text processing, input/output operations and data representation in applications offering a versatile toolset with built-in methods for efficient manipulation and formatting of textual information.

Creating Strings

每种字符串创建方法,即 '、"、""" 都具有自己的用例,具体取决于我们是否需要在字符串中包含引号、处理多行文本或我们 Python 代码中的其他特定格式要求。

Each type of string creation method i.e. ', ", """ has its own use case depending on whether we need to include quotes within the string, handle multi-line text or other specific formatting requirements in our Python code.

以下是借助三种类型的引号 '、"、""" 创建字符串的示例 −

Following is the example of creating the string with the help od three types of quotes ', ", """ −

# Single line string
single_quoted_string = 'Hello, Welcome to Tutorialspoint'

# Double quoted string
double_quoted_string = "Python Programming"

# Triple quoted string for multi-line strings
multi_line_string = """This is a
multi-line
string"""

print(single_quoted_string)
print(double_quoted_string)
print(multi_line_string)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Hello, Welcome to Tutorialspoint
Python Programming
This is a
multi-line
string

Understanding String Immutability in Python

借助以下示例,我们将了解 Python 中字符串的不可变性。

With the help of following example we are going to understand the immutability of the strings in python.

# Example demonstrating string immutability
my_string = "Hello"

# Attempting to modify a string will create a new string instead of modifying the original
modified_string = my_string + " Learners"
print(modified_string)  # Output: Hello Learners

# Original string remains unchanged
print(my_string)  # Output: Hello

# Trying to modify the string directly will raise an error
try:
   my_string[0] = 'h'  # TypeError: 'str' object does not support item assignment
except TypeError as e:
   print(f"Error: {e}")

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Hello Learners
Hello
Error: 'str' object does not support item assignment

Frozen Sets

Python 中的冻结集是集合的不可变版本。创建后,其元素不能更改、添加或删除。冻结集特别适用于那些需要集合在程序的整个执行过程中保持不变的情况,尤其是当我们想要将其用作字典中的键或另一个集合中的元素时。

A frozen set in Python is an immutable version of a set. Once created its elements cannot be changed, added or removed. Frozen sets are particularly useful in situations where we need a set that remains constant throughout the execution of a program especially when we want to use it as a key in a dictionary or as an element in another set.

Creating Frozen Sets

我们可以使用 frozenset() 构造函数创建一个冻结集,方法是传递一个可迭代对象,例如列表或另一个集合,作为参数。以下是创建冻结集的示例 −

We can create a frozen set using the frozenset() constructor by passing an iterable such as a list or another set as an argument. Following is the example of creating the Frozen set −

# Creating a frozen set
fset = frozenset([1, 2, 3, 4])

# Printing the frozen set
print(fset)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

frozenset({1, 2, 3, 4})

Understanding Frozen Sets Immutability in Python

以下示例显示了冻结集如何不可变,并且不允许在创建后进行修改。

Here’s an example shows how frozensets being immutable and do not allow modifications after creation.

# Creating a frozenset
frozen_set = frozenset([1, 2, 3, 4])

# Attempting to add an element to the frozenset will raise an error
try:
   frozen_set.add(5)
except AttributeError as e:
   print(f"Error: {e}")

# Attempting to remove an element from the frozenset will also raise an error
try:
   frozen_set.remove(2)
except AttributeError as e:
   print(f"Error: {e}")

# The original frozenset remains unchanged
print("Original frozenset:", frozen_set)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Error: 'frozenset' object has no attribute 'add'
Error: 'frozenset' object has no attribute 'remove'
Original frozenset: frozenset({1, 2, 3, 4})

Named Tuples

Python 中的命名元组是 collections 模块中可用的一种轻量级数据结构,其行为与元组相同,但允许我们使用命名属性以及索引访问其元素。

A Named tuple in Python is a lightweight data structure available in the collections module that behaves same as a tuple but allows us to access its elements using named attributes as well as indices.

它结合了元组的优点,例如不可变、内存高效,以及按名称引用元素的能力,提高了代码的可读性和可维护性。

It combines the advantages of tuples such as immutable, memory-efficient with the ability to refer to elements by name, enhancing readability and maintainability of code.

Creating Named Tuples

我们可以使用 collections 模块中的 namedtuple() 工厂函数定义一个命名元组。它接受两个参数,例如作为命名元组类型的名称和序列,即字符串的字段名称或字符串的可迭代对象,指定其字段的名称。

we can define a named tuple using the *namedtuple() *factory function from the collections module. It takes two arguments such as a name for the named tuple type and a sequence i.e. string of field names or iterable of strings which specifies the names of its fields.

from collections import namedtuple

# Define a named tuple type 'Point' with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])

# Create an instance of Point
p1 = Point(1, 2)

# Access elements by index (like a tuple)
print(p1[0])

# Access elements by name
print(p1.x)
print(p1.y)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

1
1
2

Understanding Named Tuples Immutability in Python

Python 中的命名元组是由 collections.namedtuple 工厂函数提供的,实际上是不可变的。它们的行为类似于常规元组,但有命名字段,使其更易于阅读和自文档化。

The Named tuples in Python are provided by the collections.namedtuple factory functions are indeed immutable. They behave similarly to regular tuples but have named fields by making them more readable and self-documenting.

from collections import namedtuple

# Define a named tuple called Point with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])

# Create an instance of Point
p = Point(x=1, y=2)
print(p)
# Attempt to modify the named tuple
# This will raise an AttributeError since named tuples are immutable
try:
   p.x = 10
except AttributeError as e:
   print(f"Error occurred: {e}")

# Accessing elements in a named tuple is similar to accessing elements in a regular tuple
print(p.x)
print(p.y)

执行以上代码,我们将获得以下 output -

On executing the above code we will get the following output

Point(x=1, y=2)
Error occurred: can't set attribute
1
2