简体   繁体   English

从字典 Python 内的列表中删除元素

[英]Remove element from list inside a dict Python

Hello i have a dict like this one :你好,我有一个这样的字典:

{
   "a":{
      "a1":val,
      "a2":val
   },
   "b":{
      "b1":[
          {
             "measure":{
                 "k":"v",
                 "k1":"v"
             },
             "ts":"2020-10-12T12:12:12"
          },
          {
             "measure":{
                 "k":"v",
                 "k1":"v"
             },
             "ts":"2020-10-12T12:12:12"
          },
      ]
   }
}

I need to remove some dicts from the list of dicts dict["b"]["b1"]我需要从字典列表中删除一些字典 dict["b"]["b1"]

so i imagined my code like this :所以我想象我的代码是这样的:

def epc_avionics_treatment(self,dict_data):
    i=0
    for epc1 in dict_data["b"]["b1"]:
        if (epc1["ts"]=="200-00-00T00:00:00Z"):
            del dict_data["b"]["b1"][i]
        i=i+1
    
        
    if (len(dict_data["b"]["b1"])==0):
        del dict_data["b"]["b1"]
    return dict_data

However elements from the list are not removed even if "ts" key equals to my criteria of removal i also tried to assign dict["b"]["b1"] to vars but it has no impact.然而,即使“ts”键等于我的删除标准,列表中的元素也不会被删除,我也尝试将 dict["b"]["b1"] 分配给 vars,但它没有影响。

It is happening because when you are deleting the element you dont need to increment your index var.这是因为当您删除元素时,您不需要增加索引变量。
Working example:工作示例:

def epc_avionics_treatment(dict_data):
    i=0
    while i<len(dict_data["b"]["b1"]):
        if (dict_data["b"]["b1"][i]["ts"]=="200-00-00T00:00:00Z"):
            del dict_data["b"]["b1"][i]
            i-=1
        i=i+1
    
        
    if (len(dict_data["b"]["b1"])==0):
        del dict_data["b"]["b1"]
    return dict_data

Your code is experiencing a logical error.您的代码遇到逻辑错误。 When you delete a node by following commands当您通过以下命令删除节点时

del dict_data["b"]["b1"][i]

and then increasing the i, you are going wrong because you are skipping one another node.然后增加 i,你会出错,因为你正在跳过另一个节点。 I'm going to explain it in the below :我将在下面解释它:

items = [a1,a2,a3,a4,a5]

i=3 // So items[2] : a3

// lets delete items[i]

del items[i] // a3 has been removed.

// now , items[i] is a4 ( i have not increased i yet ), so what happen if i increase the i ? 
i = i + 1 // now items[i] is a5 and i have skipped a4

//if i delete items[i], a5 would be removed and not a4




声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM