Python Set copy() 方法



Python Set copy() 方法用于创建该集的浅表副本。这意味着它返回一个包含原始集的所有元素的新集,但是一个不同的对象。元素本身不会被复制,这意味着如果元素是可变对象,那么对这些对象的更改将反映在原始和复制的集合中。

语法

以下是 Python Set copy() 方法的语法和参数 -


 original_set.copy()

参数

此方法不采用任何参数。

返回值

此方法返回原始集的副本。

示例 1

以下是 Python Set copy() 方法的基本示例,它显示了复制一组简单的整数 -


# Original set
original_set = {1, 2, 3, 4, 5}

# Create a copy of the set
copied_set = original_set.copy()

# Print both sets
print("Original Set:", original_set) 	
print("Copied Set:", copied_set) 	 	 	

# Verify that the sets are distinct objects
print(original_set is copied_set) 	 	

输出

Original Set: {1, 2, 3, 4, 5}
Copied Set: {1, 2, 3, 4, 5}
False

示例 2

在 sets 中,copy() 方法应用浅拷贝,这意味着拷贝集中的更改不会应用于原始集。此示例创建一个集,其中元组 (3, 4) 作为其元素之一,使其可哈希。然后制作该集的浅表副本,表明修改复制的集不会影响原始集 -


# Define a set with a tuple (instead of a list) as an element
original_set = {1, 2, (3, 4), 5}

# Make a shallow copy of the set
copied_set = original_set.copy()

# Print both sets
print("Original Set:", original_set) 	# Output: {1, 2, (3, 4), 5}
print("Copied Set:", copied_set) 	 	 	# Output: {1, 2, (3, 4), 5}

# Verify that the sets are distinct objects
print(original_set is copied_set) 	 	 # Output: False

# Modify the tuple inside the copied set (Note: Tuples are immutable)
# This will create a new tuple with modified contents, not affecting the original set
copied_set.remove((3, 4))
copied_set.add((6, 7))

# Print both sets after modification
print("Original Set after modification:", original_set) 	# Output: {1, 2, (3, 4), 5}
print("Copied Set after modification:", copied_set) 	 	 	# Output: {1, 2, (6, 7), 5}

# Verify that modifying the copied set does not affect the original set
print(original_set == copied_set) 	 	 # Output: False

输出

Original Set: {1, 2, 5, (3, 4)}
Copied Set: {1, 2, 5, (3, 4)}
False
Original Set after modification: {1, 2, 5, (3, 4)}
Copied Set after modification: {1, 2, 5, (6, 7)}
False

示例 3

下面的示例突出显示,如果元素是可变的,并且可变性在原始集和复制集之间共享 -


# 带有可变对象的原始集合
original_set = {1, 2, 3, (4, 5)}

# 创建集合的副本
copied_set = original_set.copy()

# 验证这些集合是否是不同的对象
print(original_set is copied_set) 	 		

# 将元素添加到复制的集合中
copied_set.add(6)
print("Original Set after adding to copied set:", original_set) 	
print("Copied Set after adding to copied set:", copied_set) 	 	 	

# 从复制的集合中删除元素
copied_set.remove(2)
print("Original Set after removing from copied set:", original_set) 	
print("Copied Set after removing from copied set:", copied_set) 	 	 	

输出

False
Original Set after adding to copied set: {3, 1, (4, 5), 2}
Copied Set after adding to copied set: {1, 2, 3, 6, (4, 5)}
Original Set after removing from copied set: {3, 1, (4, 5), 2}
Copied Set after removing from copied set: {1, 3, 6, (4, 5)}