如何在Python中把列表添加到集合中(教程)

917 阅读4分钟

How to Add List to Set in Python

Python 集合用于在一个单一的变量中保存多个元素。集合不包含重复的元素。所以,如果你想存储唯一的元素,那么就使用set数据结构。你可以向集合中添加单个或多个元素。让我们看看如何将一个列表添加到集合中。

在 Python 中向集合添加列表

要在 Python 中向集合添加一个列表,请使用 set.update() 函数。set.update() 是一个内置的 Python 函数,它接受单个元素或多个可迭代序列作为参数并将其添加到集合中。

语法

set.update(element or sequence)

参数

update() 方法接受一个单一元素或一个序列作为参数。

例子

让我们定义一个集合并将该集合添加到一个列表中

num_set = {11, 21, 19, 18, 46}

# List of numbers
num_list = [111, 118, 119, 200, 121, 129, 146]

# Add all elements of a list to the set
num_set.update(num_list)
print('Modified Set: ')
print(num_set)

输出

Modified Set: {129, 200, 11, 18, 19, 146, 21, 46, 111, 118, 119, 121}

在这个例子中,我们将一个列表作为参数传递给update()函数,它将列表中的所有元素添加到集合中。

需要记住的一点是,这个集合包含唯一的元素。如果它发现重复的元素,那么它将从集合中删除重复的元素。

因此,在集合中不存在的元素被添加,而重复的元素只是被跳过。

使用add()函数和for循环

set.add()是一个内置的函数,它接收一个单一的元素作为参数,并将该元素添加到集合中。如果你传递列表或其他迭代变量,那么它将会失败。

语法

set.add(element)

参数

set.add()方法接受一个单一元素作为参数,并将该元素添加到集合中。但是这个元素必须是不可变的。

例子

让我们只用set.add()函数将一个列表添加到set中,看看我们会得到什么。

num_set = {11, 21, 19, 18, 46}

# List of numbers
num_list = [111, 118, 119, 200, 121, 129, 146]

# Add all elements of a list to the set
num_set.add(num_list)
print('Modified Set: ')
print(num_set)

输出

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/app.py", line 7, in <module>
    num_set.add(num_list)
TypeError: unhashable type: 'list'

我们得到TypeError: unhashable type: 'list'. 这意味着我们不能单独使用add()函数来向set添加一个列表。为了解决这个问题,我们将使用for循环

我们将使用for循环遍历列表中的所有元素,并将每个项目作为参数传递给add()函数。

如果这个项目还没有出现在集合中,它将被添加到集合中。

num_set = {11, 21, 19, 18, 46}

# List of numbers
num_list = [111, 118, 119, 200, 121, 129, 146]

for item in num_list:
    num_set.add(item)
print('Modified Set: ')
print(num_set)

输出

Modified Set: {129, 200, 11, 18, 19, 146, 21, 46, 111, 118, 119, 121}

使用 add() 和 union() 函数

set union()是一个内置的Python方法,它返回一个新的集合,其中包含所有集合的唯一元素。请看下面的例子。

num_set = {11, 21, 19, 18, 46}

# List of numbers
num_list = [111, 118, 119, 200, 121, 129, 146]

num_set = num_set.union(set(num_list))
print('Modified Set: ', num_set)

输出结果

Modified Set:  {129, 200, 11, 46, 111, 18, 19, 146, 21, 118, 119, 121}

你可以看到,我们将我们的列表转换为集合,并将其作为参数传递给union()函数。

union() 方法返回一个包含两个集合元素的集合。

使用 | 操作符

操作符用于获取两个集合的联合。

num_set = {11, 21, 19, 18, 46}

# List of numbers
num_list = [111, 118, 119, 200, 121, 129, 146]

num_set |= set(num_list)
print('Modified Set: ', num_set)

输出

Modified Set:  {129, 200, 11, 46, 111, 18, 19, 146, 21, 118, 119, 121}

本教程就到此为止。

The postHow to Add List to Set in Pythonappeared first onAppDividend.