要避免Python集合操作中的錯誤,可以遵循以下幾點建議:
{}
或 set()
函數創建集合。確保集合中的元素是唯一的且不可變(如數字、字符串或元組),因為集合不能包含可變對象(如列表)。my_set = {1, 2, 3}
another_set = set([1, 2, 3])
&
(交集)、|
(并集)、-
(差集)和 ^
(對稱差集)。確保在操作符兩側使用集合。set_a = {1, 2, 3}
set_b = {2, 3, 4}
intersection = set_a & set_b # {2, 3}
union = set_a | set_b # {1, 2, 3, 4}
difference = set_a - set_b # {1}
symmetric_difference = set_a ^ set_b # {1, 4}
# 錯誤示例
my_set = {1, 2, 3}
my_set.add([4]) # TypeError: unhashable type: 'list'
print(my_set[0]) # TypeError: 'set' object does not support indexing
my_list = [1, 2, 3, 4, 5]
even_numbers = {x for x in my_list if x % 2 == 0} # {2, 4}
len()
、max()
、min()
和 sum()
,可用于處理集合。確保在調用這些函數時使用集合。my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # 5
print(max(my_set)) # 5
print(min(my_set)) # 1
print(sum(my_set)) # 15
遵循這些建議,可以幫助您避免Python集合操作中的錯誤。