Python 简明教程

Python - Access Set Items

Access Set Items

访问集合项目的主要方法是使用诸如 for loop 的循环遍历集合。通过迭代集合,你可以逐个访问每个元素,并在需要时对其执行操作。

The primary way to access set items is by traversing the set using a loop, such as a for loop. By iterating over the set, you can access each element one by one and perform operations on them as needed.

在 Python 中, sets 是唯一元素的无序集合,与序列(例如 liststuples )不同,集合不对其元素进行位置索引。这意味着你不能通过指定索引直接访问集合的各个元素。

In Python, sets are unordered collections of unique elements, and unlike sequences (such as lists or tuples), sets do not have a positional index for their elements. This means that you cannot access individual elements of a set directly by specifying an index.

此外,集合没有与元素关联的键,就像 dictionaries 那样。在字典中,每个元素都与一个键配对,允许你访问与特定键关联的值。然而,集合没有这种键值配对。

Additionally, sets do not have keys associated with their elements, as dictionaries do. In a dictionary, each element is paired with a key, allowing you to access the value associated with a specific key. However, sets do not have this key-value pairing.

因此,要访问集合的元素,我们需要使用 for 循环(或列表解析)

Therefore, to access the elements of a set we need to use for loop (or, List Comprehension )

Access Set Items Using For Loop

Python 中的 for 循环是一种控制流语句,用于遍历序列,并对序列中的每个元素执行一段代码。该循环将持续到处理完所有元素为止。

A for loop in Python is a control flow statement used for iterating over a sequence and executing a block of code for each element in the sequence. The loop continues until all elements have been processed.

我们可以通过依次遍历集合中的每个元素,使用 for 循环访问集合项目。由于集合是唯一元素的无序集合,因此 for 循环提供了一种遍历集合并逐个访问每个元素的便捷方式。

We can access set items using a for loop by iterating over each element in the set sequentially. Since sets are unordered collections of unique elements, a for loop provides a convenient way to traverse the set and access each element one by one.

Example

在下面的示例中,for 循环迭代集合“langs”,在每次迭代中,变量“lang”被赋予当前元素的值 −

In the following example, the for loop iterates over the set "langs", and in each iteration, the variable "lang" is assigned the value of the current element −

# Defining a set
langs = {"C", "C++", "Java", "Python"}

# Accessing set items using a for loop
for lang in langs:
   print (lang)

它将生成如下输出:

It will produce the following output −

Python
C
C++
Java

Access Set Items Using List Comprehension

列表解析是一种在 Python 中创建列表的高效方法。它允许你将表达式应用于可迭代中的每个项目来生成新列表,并可以选择包含一个用于筛选元素的条件。

List comprehension is an efficient way to create lists in Python. It allows you to generate a new list by applying an expression to each item in an iterable, optionally including a condition to filter elements.

我们可以通过在解析中将集合转换为列表来使用列表解析访问集合项目。这允许你遍历集合元素并对它们执行操作,类似于使用 for 循环。

We can access set items using list comprehension by converting the set into a list within the comprehension. This allows you to iterate over the set elements and perform operations on them, similar to using a for loop.

Example

在这个示例中,我们使用列表解析通过在 "my_set" 的每个元素上迭代来访问集合项−

In this example, we are using list comprehension to access set items by iterating over each element of "my_set" −

my_set = {1, 2, 3, 4, 5}
# Accessing set items using list comprehension
accessed_items = [item for item in my_set]
print(accessed_items)

我们得到了如下输出 −

We get the output as shown below −

[1, 2, 3, 4, 5]

Access Subset From a Set

在数学上,子集是一个集合,它只包含另一集合中也包含的元素。换句话说,子集的每个元素也是原始集合的一个元素。如果集合 A 的每个元素也是集合 B 的元素,则 A 被认为是 B 的子集,表示为 A ⊆ B

Mathematically, a subset is a set that contains only elements that are also contained in another set. In other words, every element of the subset is also an element of the original set. If every element of set A is also an element of set B, then A is considered a subset of B, denoted as A ⊆ B.

在 Python 中,可以使用集合运算或通过遍历幂集(所有子集的集合)和基于特定条件进行筛选来从集合中访问子集。

In Python, you can access subsets from a set using set operations or by iterating over the power set (the set of all subsets) and filtering based on specific criteria.

  1. Using Set Operations − You can use built-in set operations such as issubset() function to check if one set is a subset of another.

  2. Iterating Over Power Set − Iterate over all possible subsets of the set and filter based on certain criteria to access specific subsets.

Example

以下是演示如何从集合访问子集的基本示例−

Following is the basic example demonstrating how to access subsets from a set −

import itertools

# Defining a set
original_set = {1, 2, 3, 4}

# Checking if {1, 2} is a subset of the original set
is_subset = {1, 2}.issubset(original_set)
print("{1, 2} is a subset of the original set:", is_subset)

# Generating all subsets with two elements
subsets_with_two_elements = [set(subset) for subset in itertools.combinations(original_set, 2)]
print("Subsets with two elements:", subsets_with_two_elements)

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

Following is the output of the above code −

{1, 2} is a subset of the original set: True
Subsets with two elements: [{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}]

Checking if Set Item Exists

您可以使用 Python’s membership operatorsinnot in 检查集合中是否提供某个项。

You can check whether a certain item is available in the set using the Python’s membership operators, in and not in.

in 运算符在集合中找到指定元素后,返回 True ;否则,返回 False 。相反, not in 运算符在集合中不存在元素时,返回 True ;如果存在,返回 False

The in operator returns True if the specified element is found within the collection, and False otherwise. Conversely, the not in operator returns True if the element is not present in the collection, and False if it is.

Example

在下面的示例中,“in”运算符验证项“Java”是否存在于集合“langs”中,“not in”运算符检查项“SQL”是否不存在于集合中−

In the below example, the "in" operator verifies whether the item "Java" exists in the set "langs", and the "not in" operator checks whether the item "SQL" does not exist in the set −

# Defining a set
langs = {"C", "C++", "Java", "Python"}

# Checking if an item exists in the set
if "Java" in langs:
    print("Java is present in the set.")
else:
    print("Java is not present in the set.")

# Checking if an item does not exist in the set
if "SQL" not in langs:
    print("SQL is not present in the set.")
else:
    print("SQL is present in the set.")

它将生成如下输出:

It will produce the following output −

Java is present in the set.
SQL is not present in the set.