Python 程序 - 如果特定值不存在,则从字典列表中删除字典
当需要从字典列表中删除字典时,其中不存在特定值时,将使用简单迭代、'del'运算符和'break'语句。
示例
以下是相同的演示-
my_list = [{"code" : 1, "fun" : "learn"},
{"code" : 2, "fun" : "code"},
{"code" : 3, "fun" : "test"},
{"code" : 4, "fun" : "teach"},
{"code" : 4, "fun" : "make"},
{"code" : 4, "fun" : "object"}]
print("字典列表是: " )
print(my_list)
for index in range(len(my_list)):
if my_list[index]['code'] == 3:
del my_list[index]
break
print("结果列表是: ")
print(my_list)输出结果字典列表是:
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 3, 'fun': 'test'}, {'code': 4, 'fun': 'teach'},
{'code': 4, 'fun': 'make'}, {'code': 4, 'fun': 'object'}]
结果列表是:
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 4, 'fun': 'teach'}, {'code': 4, 'fun': 'make'},
{'code': 4, 'fun': 'object'}]解释
定义了一个字符串列表并显示在控制台上。
迭代列表,并检查特定索引是否等于整数。
这被分配给结果。
这在控制台上显示为输出。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下