Python - 清除列表作为字典值
pythonserver side programmingprogramming更新于 2025/8/15 9:48:17
在本文中,我们考虑一个字典,其中的值以列表形式呈现。然后我们考虑从列表中清除这些值。这里我们有两种方法。一种是使用清除方法,另一种是使用列表推导为每个键指定空值。
示例
x1 = {"Apple" : [4,6,9,2],"Grape" : [7,8,2,1],"Orange" : [3,6,2,4]}
x2 = {"mango" : [4,6,9,2],"pineapple" : [7,8,2,1],"cherry" : [3,6,2,4]}
print("给定的输入是:" + str(x1))
# 使用 loop + clear()
for k in x1:
x1[k].clear()
print("清除列表作为字典值是 : " + str(x1))
print("\n给定的输入是 : " + str(x2))
# 使用字典推导式
x2 = {k : [] for k in x2}
print("清除列表作为字典值是 : " + str(x2))
输出
运行上述代码得到以下结果 −
给定的输入是:{'Apple': [4, 6, 9, 2], 'Grape': [7, 8, 2, 1], 'Orange': [3, 6, 2, 4]}
清除列表作为字典值是: {'Apple': [], 'Grape': [], 'Orange': []}
给定的输入是:{'mango': [4, 6, 9, 2], 'pineapple': [7, 8, 2, 1], 'cherry': [3, 6, 2, 4]}
清除列表作为字典值是:{'mango': [], 'pineapple': [], 'cherry': []}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

