Python中的set(集合)是一种无序且不包含重复元素的数据结构。以下是set的一些常见使用场景:
去重:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
成员资格测试:
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # 输出: True
print(6 in my_set) # 输出: False
消除重复:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
unique_set = set1.union(set2) # 结果: {1, 2, 3, 4, 5}
集合运算:
setA = {1, 2, 3}
setB = {3, 4, 5}
print(setA.union(setB)) # 输出: {1, 2, 3, 4, 5}
print(setA.intersection(setB)) # 输出: {3}
print(setA.difference(setB)) # 输出: {1, 2}
print(setA.symmetric_difference(setB)) # 输出: {1, 2, 4, 5}
字典键:
my_dict = {frozenset([1, 2]): 'value1', frozenset([3, 4]): 'value2'}
生成唯一序列:
import random
my_set = {1, 2, 3, 4, 5}
unique_random_elements = random.sample(my_set, len(my_set))
集合推导式:
my_list = [1, 2, 3, 4, 5]
my_set = {x for x in my_list}
跟踪元素出现次数:
from collections import Counter
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(my_list)
print(counter) # 输出: Counter({4: 4, 3: 3, 2: 2, 1: 1})
这些只是Python set的一些常见用途。根据具体需求,set还可以用于其他场景。