说说在 Python 中,如何复制列表或字典

243 阅读1分钟

有时候,我们可能不希望函数修改所传入的列表或字典。那么我们可以使用 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 列表中的值被改变。