Python Set Copy()方法示例教程
Python Set copy()是一個內置方法,用於複製該集合的淺表副本。 copy()方法複製該集合。在知道copy()之前,讓我告訴我們我們也可以使用「 =」運算符將一個集合複製到另一個集合。但是這種方法存在一些問題。就像,如果我們修改新的設置,舊的設置也會被修改。因此,如果我們不想修改原始集合,則應使用Python set()方法。
Python設置Copy()
該方法用於將完整的設置項目複製到全新的設置中。
句法
new_set = original_set.copy()
在這裡,new_set是要在其中複製的集,而original_set是要保持不變的舊集。
返回值
set.copy()方法不返回任何值,它只是將原始集合複製到新集合。
請參見以下代碼示例。
# app.py # Writing char by char in a set set1 = {'C', 'o', 'd', 'i', 'n', 'g'} print("Before copy the set is: ", set1) # Now we will copy this set to a new set named Set2 # Using = operator set2 = set1 print("The new set is: ", set2) # Now we will modify the new set set2.add('H') set2.add('i') # Printing both the set print("After copying Old set is: ", set1) print("After copying New set is: ", set2)
輸出量
Before copy the set is: {'o', 'd', 'n', 'C', 'g', 'i'} The new set is: {'o', 'd', 'n', 'C', 'g', 'i'} After copying Old set is: {'o', 'd', 'n', 'C', 'H', 'g', 'i'} After copying New set is: {'o', 'd', 'n', 'C', 'H', 'g', 'i'}
因此,在此示例中,我們可以看到,當我們修改新集合時,原始集合也被修改了。
現在,讓我們了解copy()方法,在這裡我們可以保持原始設置不變。
例子2
# app.py # Writing char by char in a set set1 = {'C', 'o', 'd', 'i', 'n', 'g'} print("Before copy the set is: ", set1) # Now we will copy this set to a new set named Set2 # Using copy() method set2 = set1.copy() print("The new set is: ", set2) # Now we will modify the new set set2.add('H') set2.add('i') # Printing both the set print("After copying Old set is: ", set1) print("After copying New set is: ", set2)
輸出量
Before copy the set is: {'d', 'g', 'n', 'i', 'o', 'C'} The new set is: {'i', 'd', 'g', 'o', 'n', 'C'} After copying Old set is: {'d', 'g', 'n', 'i', 'o', 'C'} After copying New set is: {'i', 'H', 'd', 'g', 'o', 'n', 'C'}
因此,在此示例中,我們可以看到,儘管我們對新集合進行了更改,但舊集合保持不變。這是set copy()方法的優點。
也可以看看
Python設置add()
Python設置clear()