摘要:使用 set带大括号 {}employee_ids = set([1, 2, 3, 4, 5, 5])print(employee_ids)# {1, 2, 3, 4, 5}
Python 中的集合至关重要,也是 Python 中最常用的内置数据类型之一。
集合具有一些主要属性。
集合中的元素必须是唯一的。套装中不允许有重复项。它们是无序的设置项目不可更改,但您可以删除和添加新项目。可以使用两个选项创建集合。
使用 set带大括号 {}employee_ids = set([1, 2, 3, 4, 5, 5])print(employee_ids)# {1, 2, 3, 4, 5}在上面的例子中,写了两次 5,但当打印集合时可以看到没有重复——只有一个 5。
可以通过将逗号分隔的元素序列括在大括号内来直接创建集合。
employee_ids = {1, 2, 3, 4, 5, 5}print(employee_ids)# {1, 2, 3, 4, 5}但是在这里必须小心,如果我们想创建一个空集合,应该使用函数set,因为空的大括号创建的是字典,而不是集合。
现在通过示例来发现最常用的集合方法。
Add(元素)将元素添加到集合中。
employee_ids = {1, 2, 3, 4, 5}print(employee_ids)employee_ids.add(6)print(employee_ids)# {1, 2, 3, 4, 5}# {1, 2, 3, 4, 5, 6}2. renmove(元素)
从集合中移除指定的元素。如果未找到该元素,则引发 KeyError
employee_ids = {1, 2, 3, 4, 5}employee_ids.remove(3)print(employee_ids)# {1, 2, 4, 5}employee_ids.remove(333)# KeyError: 3333. discard(元素)
从集合中删除指定的元素(如果存在)。如果未找到该元素,则不会引发错误。
employee_ids = {1, 2, 3, 4, 5}print(employee_ids)employee_ids.remove(3)print(employee_ids)# {1, 2, 3, 4, 5}employee_ids.discard(333)print(employee_ids)# {1, 2, 3, 4, 5}4. 并集
返回一个新集,其中包含其他集的项的唯一列表。
employee_ids_part1 = {1, 2, 3, 4, 5}employee_ids_part2 = {4, 5, 6, 7, 8}employee_ids_part3 = {7, 8, 9, 10, 11}full = employee_ids_part1.union(employee_ids_part2, employee_ids_part3)print(full)# {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}交集返回一个新集合,其中包含两个集合的公共元素。
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}art_courses = {'History', 'Math', 'Art', 'Design'}common_courses = cs_courses.intersection(art_courses)print(common_courses)# {'Math', 'History'}集合差返回一个新集,其中包含调不在指定集中的元素。
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}art_courses = {'History', 'Math', 'Art', 'Design'}difference = cs_courses.difference(art_courses)print(difference)# {'Physics', 'CompSci'}7. 对称差
返回一个新集,其中包含每个集唯一的元素。当想要处理集合之间的差异并且不关心公共元素时,对称差异非常有用。在处理配置、选项或首选项时,通常会出现这种情况。
user_preferences1 = {'theme', 'language', 'fontSize'}user_preferences2 = {'language', 'fontSize', 'timezone'}difference_preferences = user_preferences1.symmetric_difference(user_preferences2)print(difference_preferences)# {'theme', 'timezone'}判断是否为子集如果给定集和是另一个集合的子集,则此方法返回 True。
current_users = {'john', 'alice', 'bob', 'mary'}authorized_users = {'john', 'alice', 'dave', 'mary', 'mike', 'bob', 'susan'}is_everyone_authorized = current_users.issubset(authorized_users)print(is_everyone_authorized)# True复制返回给定集合的浅表副本。
original_set = {1, 2, 3}copied_set = original_set.copy# Result: {1, 2, 3}10. 判断两个集合是否有相同元素)
返回 True:如果两个集合不相交,则表示给定集合之间没有公共元素。
set1 = {1, 2, 3}set2 = {4, 5, 6}result = set1.isdisjoint(set2)print(result)# Result: Trueset3 = {1, 2, 3}set4 = {3, 4, 5}result_new = set3.isdisjoint(set4)print(result_new)# Result: False来源:自由坦荡的湖泊AI
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!