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
廣告