Python中的集合(set)是一种无序且不重复的数据结构,它可以用于存储多个元素。集合可以用于解决很多问题,以下是一些常见的应用场景及相应的代码示例:
nums = [1, 2, 3, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums) # {1, 2, 3, 4, 5}
fruits = {'apple', 'banana', 'orange'}
print('apple' in fruits) # True
print('grape' in fruits) # False
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
print(union_set) # {1, 2, 3, 4}
print(intersection_set) # {2, 3}
print(difference_set) # {1}
nums = [1, 2, 3, 4, 5]
exclude_set = {2, 3}
filtered_nums = [num for num in nums if num not in exclude_set]
print(filtered_nums) # [1, 4, 5]
s = 'hello world'
unique_chars = set(s)
print(len(unique_chars)) # 8
注意:集合是无序的,因此不能通过索引访问集合中的元素。如果需要有序的数据结构,应该使用列表(list)或元组(tuple)。
本文由 mdnice 多平台发布