創建一個集合:{}
您可以使用Curly Braces set()
或
# Using curly braces my_set = {1, 2, 3, 3, 4, 5} # Duplicates are automatically removed print(my_set) # Output: {1, 2, 3, 4, 5} # Using the set() constructor my_list = [1, 2, 2, 3, 4, 4, 5] my_set = set(my_list) print(my_set) # Output: {1, 2, 3, 4, 5}
<>添加和刪除元素:您可以使用add()
方法添加元素,並使用remove()
>或discard()
方法刪除元素。 如果找不到該元素,則remove()
KeyError
discard()
my_set.add(6) print(my_set) # Output: {1, 2, 3, 4, 5, 6} my_set.remove(3) print(my_set) # Output: {1, 2, 4, 5, 6} my_set.discard(7) # No error even though 7 is not present print(my_set) # Output: {1, 2, 4, 5, 6}
|
&
-
設置操作:^
),Intersection((<>>),差異(
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # or set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5} intersection_set = set1 & set2 # or set1.intersection(set2) print(intersection_set) # Output: {3} difference_set = set1 - set2 # or set1.difference(set2) print(difference_set) # Output: {1, 2} symmetric_difference_set = set1 ^ set2 # or set1.symmetric_difference(set2) print(symmetric_difference_set) # Output: {1, 2, 4, 5}
TypeError
>,但是,如果需要將不同數據類型的集合存儲在一起,則可以使用一組元組。 例如:在這種情況下,
# Using curly braces my_set = {1, 2, 3, 3, 4, 5} # Duplicates are automatically removed print(my_set) # Output: {1, 2, 3, 4, 5} # Using the set() constructor my_list = [1, 2, 2, 3, 4, 4, 5] my_set = set(my_list) print(my_set) # Output: {1, 2, 3, 4, 5}
>
以上是如何將Python集用於唯一數據?的詳細內容。更多資訊請關注PHP中文網其他相關文章!