Python中的集合(set)是一個無序的、不重復的元素序列。要有效地利用集合的特性,你可以遵循以下幾點:
my_list = [1, 2, 3, 4, 4, 5, 6, 6, 7]
unique_list = list(set(my_list))
print(unique_list) # 輸出:[1, 2, 3, 4, 5, 6, 7]
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # 輸出:True
print(6 in my_set) # 輸出:False
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# 交集
intersection = set_a.intersection(set_b)
print(intersection) # 輸出:{3, 4}
# 并集
union = set_a.union(set_b)
print(union) # 輸出:{1, 2, 3, 4, 5, 6}
# 差集
difference = set_a.difference(set_b)
print(difference) # 輸出:{1, 2}
# 對稱差集
symmetric_difference = set_a.symmetric_difference(set_b)
print(symmetric_difference) # 輸出:{1, 2, 5, 6}
my_set = {4, 2, 9, 7, 5, 1, 8, 3, 6}
for item in my_set:
print(item)
my_set = {4, 2, 9, 7, 5, 1, 8, 3, 6}
my_list = list(my_set)
my_tuple = tuple(my_set)
print(my_list) # 輸出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_tuple) # 輸出:(1, 2, 3, 4, 5, 6, 7, 8, 9)
squares = {x**2 for x in range(1, 11)}
print(squares) # 輸出:{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
了解并充分利用這些集合特性,可以幫助你更有效地處理數據。