Python中列表List转换为集合Set的五种不同方法

Python 中将列表转换为集合的5个方法:

  1. set() 构造函数
  2. Set Comprehension
  3. for 循环
  4. map() 函数
  5. *解包操作符

1、set() 构造函数
这是直接将 Python list 转换为集合的最常用方法。内置的 set() 构造函数接收一个可迭代对象(如 list),并返回其等价集合,同时自动删除任何重复的对象。

bands_list = ["Nirvana", "Aerosmith", "Eagles", "Nirvana", "Metallica", "Aerosmith"]
print('The list: ', bands_list)
unique_bands = set(bands_list)
print('The set: ', unique_bands)

使用 set() 构造函数可以直接将列表转换为 Python 中的集合,自动省略重复的频带,确保每个元素都是唯一的。

2、set comprehension
Set comprehension 为在 Python 中创建集合提供了一种简洁的方法,类似于list comprehension 对列表list的作用。当需要在转换过程中对 Python 列表元素进行过滤或应用转换时,它非常有用。

cities = ["Los Angeles", "New York", "San Francisco", "Houston", "San Diego"]
print('The List:',cities)
california_cities = {city for city in cities if
"San" in city}
print('The set:', california_cities)

该Set comprehension筛选器只包含带有 "San "字样的城市(表明一些典型的加利福尼亚城市)。这是用 Python 过滤列表并将其转换为集合的简洁方法。

3、for 循环
这种手动方法涉及遍历 Python 列表,并使用 for 循环将每个元素添加到一个集合中。这种方法简单明了,并允许在转换过程中进行额外的逻辑或检查。

monuments_list = ["Statue of Liberty", "Mount Rushmore", "Statue of Liberty", "Lincoln Memorial"]
print('The list:', monuments_list)
monuments_set = set()

for monument in monuments_list:
    monuments_set.add(monument)

print('The set:', monuments_set)

Python 列表 monuments_list 包含多个重复的monument。我们初始化一个空的 Python 集 monuments_set,然后循环查看列表中的每个monument。如果该monument尚未在 Python 集合中(集合本身不允许重复),则将其添加进来。这种方法简单明了,利用循环来建立一个唯一不重复的monument集。

4、map()函数
Python 中的 map() 函数会对列表中的每个项应用一个函数。当我们想在将每个列表项转换为 Python 集合之前对其进行转换时,它是理想的选择。映射后,结果列表将传递给 set() 进行转换。

presidents = ["George Washington", "Thomas Jefferson", "Abraham Lincoln"]
print('The list:', presidents)
first_names = set(map(lambda name: name.split()[0], presidents))
print('The set:', first_names)

Python 列表的 Presidents 由全名组成。使用 map() 函数,我们应用 lambda 函数分割每个全名,只选择第一部分(即名字)。然后将转换后的列表转换为集合,以保留唯一的名字。

这样,就可以使用 map() 和 lambda 函数将 Python list 转换为集合。

5、使用* 解包操作符
在 Python 3.5+ 中引入的 * 解包操作符(unpacking operator)可用于将列表项直接解包到集合中。这是一种将列表元素传递到集合中的快速且 Pythonic 的方法。

east_coast = ["Miami Beach", "Myrtle Beach"]
west_coast = [
"Venice Beach", "Malibu Beach"]
all_beaches = {*east_coast, *west_coast}
print('Combined Set:', all_beaches)

我们有两个 Python 列表:east_coast 和 west_coast,分别代表两个coast的海滩beache。解包操作符 (*) 用于将两个列表中的项目直接合并和解包到一个集合中。这是一种将多个列表合并成一个唯一集合的简化方法。