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'}]解释
定义了一个字符串列表并显示在控制台上。
迭代列表,并检查特定索引是否等于整数。
这被分配给结果。
这在控制台上显示为输出。
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短