Python集合copy()方法



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

语法

以下是Python集合copy()方法的语法和参数:

original_set.copy()

参数

此方法不接受任何参数。

返回值

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

示例1

以下是Python集合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

在集合中,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 with a mutable object
original_set = {1, 2, 3, (4, 5)}

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

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

# Add an element to the 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)      

# Remove an element from the 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)}
python_set_methods.htm
广告
© . All rights reserved.