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()
资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载