Python中的set(集合)是一種無序且不包含重復元素的數(shù)據(jù)結(jié)構(gòu)。以下是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) # 結(jié)果: {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}
跟蹤元素出現(xiàn)次數(shù):
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的一些常見用途。根據(jù)具體需求,set還可以用于其他場景。