Python 中如何复制列表或字典

有时候,我们可能不希望函数修改所传入的列表或字典。那么我们可以使用 copy 模块的 copy() 函数。

import copy
colors = [\'红\', \'绿\', \'黄\']
other_colors = copy.copy(colors)
other_colors.append(\'蓝\')
print(\'other_colors = \' + str(other_colors))
print(\'colors = \' + str(colors))
dict = {\'evaporation\': {\'释义\': \'蒸发\', \'词性\': \'n\'},
        \'carpenter\': {\'释义\': \'木匠\', \'词性\': \'n\'}}
other_dict=copy.copy(dict)
print(\'dict = \'+str(dict))
print(\'other_dict = \'+str(other_dict))

运行结果:

other_colors = [\’红\’, \’绿\’, \’黄\’, \’蓝\’]
colors = [\’红\’, \’绿\’, \’黄\’]
dict = {\’evaporation\’: {\’释义\’: \’蒸发\’, \’词性\’: \’n\’}, \’carpenter\’: {\’释义\’: \’木匠\’, \’词性\’: \’n\’}}
other_dict = {\’evaporation\’: {\’释义\’: \’蒸发\’, \’词性\’: \’n\’}, \’carpenter\’: {\’释义\’: \’木匠\’, \’词性\’: \’n\’}}

可以看到,因为使用了复制,所以只有 other_colors 列表中的值被改变。

作者:deniro
链接:https://www.jianshu.com/p/cb26152b221b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发表评论

您的电子邮箱地址不会被公开。

Shopping Cart