创建一个集合:{}
您可以使用Curly Braces set()
或
<code class="python"># 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}</code>
添加和删除元素:您可以使用add()
方法添加元素,并使用remove()
>或discard()
方法删除元素。 如果找不到该元素,则remove()
KeyError
discard()
<code class="python">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}</code>
|
&
-
设置操作:^
),Intersection((>),差异(
<code class="python">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}</code>)和对称差异(
TypeError
>,但是,如果需要将不同数据类型的集合存储在一起,则可以使用一组元组。 例如:在这种情况下,
<code class="python"># 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}</code>,集合中的每个元素都是元组,在集合中保持类型一致性。 但是,您不能将元素与整数直接混合在一起。
>
以上是如何将Python集用于唯一数据?的详细内容。更多信息请关注PHP中文网其他相关文章!