Python 简明教程

Python - Add Set Items

Add Set Items

添加 set 项意味着将新元素包括到现有集合中。在 Python 中,集合是可变的,这意味着创建后可以修改它们。虽然集合中的元素必须不可变(例如整数、字符串或元组),但集合本身可以修改。

Adding set items implies including new elements into an existing set. In Python, sets are mutable, which means you can modify them after they have been created. While the elements within a set must be immutable (such as integers, strings, or tuples), the set itself can be modified.

可以使用多种方法向集合中添加项,例如 add()、update() 或集合运算,如并集 (|) 和集合解析。

You can add items to a set using various methods, such as add(), update(), or set operations like union (|) and set comprehension.

Add Set Items Using the add() Method

Python 中的 add() 方法用于向集合中添加单个元素。如果指定的元素不存在,它会通过插入该元素来修改集合。如果元素已在集合中,add() 方法对集合没有任何更改。

The add() method in Python is used to add a single element to the set. It modifies the set by inserting the specified element if it is not already present. If the element is already in the set, the add() method has no change in the set.

Syntax

以下是向集合中添加元素的语法 -

Following is the syntax to add an element to a set −

set.add(obj)

其中, obj 是任何不可变类型的对象。

Where, obj is an object of any immutable type.

Example

在以下示例中,我们将初始化一个名为“language”的空集合,并使用 add() 方法向其中添加元素 -

In the following example, we are initializing an empty set called "language" and adding elements to it using the add() method −

# Defining an empty set
language = set()

# Adding elements to the set using add() method
language.add("C")
language.add("C++")
language.add("Java")
language.add("Python")

# Printing the updated set
print("Updated Set:", language)

它将生成如下输出:

It will produce the following output −

Updated Set: {'Python', 'Java', 'C++', 'C'}

Add Set Items Using the update() Method

在 Python 中,集合类的 update() 方法用于向集合中添加多个元素。它通过将可迭代对象(例如另一个集合、列表、元组或字符串)中的元素添加到当前集合,从而修改集合。可迭代对象中的元素如果不已经在集合中,就将它们插入集合中。

In Python, the update() method of set class is used to add multiple elements to the set. It modifies the set by adding elements from an iterable (such as another set, list, tuple, or string) to the current set. The elements in the iterable are inserted into the set if they are not already present.

Syntax

以下是向集合中更新元素的语法 -

Following is the syntax to update an element to a set −

set.update(obj)

其中, obj 是集合或序列对象(列表、元组、字符串)。

Where, obj is a set or a sequence object (list, tuple, string).

Example: Adding a Single Set Item

在下面的示例中,我们初始化一个名为“my_set”的集合。然后,我们使用 update() 方法向集合中添加元素“4” -

In the example below, we initialize a set called "my_set". Then, we use the update() method to add the element "4" to the set −

# Define a set
my_set = {1, 2, 3}

# Adding element to the set
my_set.update([4])
# Print the updated set
print("Updated Set:", my_set)

以下是上面代码的输出: -

Following is the output of the above code −

Updated Set: {1, 2, 3, 4}

Example: Adding any Sequence Object as Set Items

update() 方法还接受任何序列对象作为参数。

The update() method also accepts any sequence object as argument.

在此示例中,我们首先定义一个集合和一个元组,即 lang1 和 lang2,其中包含不同的编程语言。然后,我们使用 update() 方法将“lang2”中的所有元素添加到“lang1” -

In this example, we first define a set and a tuple, lang1 and lang2, containing different programming languages. Then, we add all elements from "lang2" to "lang1" using the update() method −

# Defining a set
lang1 = {"C", "C++", "Java", "Python"}
# Defining a tuple
lang2 = {"PHP", "C#", "Perl"}
lang1.update(lang2)
print (lang1)

获得的结果如下所示 −

The result obtained is as shown below −

{'Python', 'C++', 'C#', 'C', 'Java', 'PHP', 'Perl'}

Example

在此示例中,集合是从一个字符串构建的,另一个字符串用作 update() 方法的参数 -

In this example, a set is constructed from a string, and another string is used as argument for update() method −

set1 = set("Hello")
set1.update("World")
print (set1)

它将生成如下输出:

It will produce the following output −

{'H', 'r', 'o', 'd', 'W', 'l', 'e'}

Add Set Items Using Union Operator

在 Python 中,并集运算符 (|) 用于在两个集合之间执行并集运算。两个集合的并集包含两个集合中存在的任何不同元素,并且不重复。

In Python, the union operator (|) is used to perform a union operation between two sets. The union of two sets contains all the distinct elements present in either of the sets, without any duplicates.

我们可以通过使用“|”运算符或 union() 函数(它将两个集合中的元素合并到一个新集合中,其中包含两个原始集合中存在的任何唯一元素)来在两个集合之间执行并集运算,从而使用并集运算符添加集合项。

We can add set items using the union operator by performing the union operation between two sets using the "|" operator or union() function, which combines the elements from both sets into a new set, containing all unique elements present in either of the original sets.

Example

以下示例使用 union() 方法和 | 运算符合并集合,以创建包含原始集合中唯一元素的新集合 -

The following example combine sets using the union() method and the | operator to create new sets containing unique elements from the original sets −

# Defining three sets
lang1 = {"C", "C++", "Java", "Python"}
lang2 = {"PHP", "C#", "Perl"}
lang3 = {"SQL", "C#"}

# Performing union operation
combined_set1 = lang1.union(lang2)
combined_set2 = lang2 | lang3

# Print the combined set
print ("Combined Set1:", combined_set1)
print("Combined Set2:", combined_set2)

以上代码的输出如下所示 −

Output of the above code is as shown below −

Combined Set1: {'C#', 'Perl', 'C++', 'Java', 'PHP', 'Python', 'C'}
Combined Set2: {'C#', 'Perl', 'PHP', 'SQL'}

Example

如果将序列对象作为 union() 方法的参数提供,则 Python 会自动先将其转换为集合,然后再执行并集 -

If a sequence object is given as argument to union() method, Python automatically converts it to a set first and then performs union −

lang1 = {"C", "C++", "Java", "Python"}
lang2 = ["PHP", "C#", "Perl"]
lang3 = lang1.union(lang2)
print (lang3)

输出结果如下:

The output produced is as follows −

{'PHP', 'C#', 'Python', 'C', 'Java', 'C++', 'Perl'}

Add Set Items Using Set Comprehension

在 Python 中,集合推导是一种使用单行代码创建集合的方法。它允许你对可迭代对象(例如列表、元组或范围)中的每个项应用一个表达式,然后生成一个新集合,可选地包含一个条件来过滤元素。

In Python, set comprehension is a way to create sets using a single line of code. It allows you to generate a new set by applying an expression to each item in an iterable (such as a list, tuple, or range), optionally including a condition to filter elements.

我们可以通过迭代可迭代对象、对每个元素应用一个表达式并在大括号 {} 中包含推导表达式来使用集合推导添加集合项,以生成包含应用于每个元素的表达式结果的新集合。

We can add set items using set comprehension by iterating over an iterable, applying an expression to each element, and enclosing the comprehension expression within curly braces {} to generate a new set containing the results of the expression applied to each element.

Example

在下面的示例中,我们定义了一个整数列表,然后使用集合推导来生成一个包含这些整数的平方值的集合 −

In the following example, we are defining a list of integers and then using set comprehension to generate a set containing the squares of those integers −

# Defining a list containing integers
numbers = [1, 2, 3, 4, 5]
# Creating a set containing squares of numbers using set comprehension
squares_set = {num ** 2 for num in numbers}
# Printing the set containing squares of numbers
print("Squares Set:", squares_set)

以下是上面代码的输出: -

Following is the output of the above code −

Squares Set: {1, 4, 9, 16, 25}