Python-清除字典值的列表
在本文中,我们考虑一个字典,它的值被表示为列表。然后我们考虑从列表中清除那些值。这里有两种方法。一种是使用 clear 方法,另一种是使用列表解析为每个键指定空值。
示例
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("The given input is : " + str(x1))
# using loop + clear()
for k in x1:
x1[k].clear()
print("Clearing list as dictionary value is : " + str(x1))
print("\nThe given input is : " + str(x2))
# using dictionary comprehension
x2 = {k : [] for k in x2}
print("Clearing list as dictionary value is : " + str(x2))输出
运行以上代码给我们以下结果 −
The given input is : {'Apple': [4, 6, 9, 2], 'Grape': [7, 8, 2, 1], 'Orange': [3, 6, 2, 4]}
Clearing list as dictionary value is : {'Apple': [], 'Grape': [], 'Orange': []}
The given input is : {'mango': [4, 6, 9, 2], 'pineapple': [7, 8, 2, 1], 'cherry': [3, 6, 2, 4]}
Clearing list as dictionary value is : {'mango': [], 'pineapple': [], 'cherry': []}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP