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'}]解释
定义了一个字符串列表并显示在控制台上。
迭代列表,并检查特定索引是否等于整数。
这被分配给结果。
这在控制台上显示为输出。
