如何从嵌套列表中的元素中删除非通用值



所以我有大量的数据存储在嵌套列表中。嵌套列表有很多子列表,但它采用以下一般形式:

nested_list = [[[ID#, Magnitude, Magnitude Error],[ID#, Magnitude, Magnitude Error]], 
               [[ID#, Magnitude, Magnitude Error],[ID#, Magnitude, Magnitude Error]]]

ID#、幅值和幅值误差都是浮动的。我还有一份常见身份证号码的清单。我想做的是删除用ID号标记的元素,该ID号不在公共ID号集中。在这一点上,基本上只有身份证号码才重要。我已经用下面的嵌套列表和数据尝试了我的代码:

nested_list = [[[1.0, 17.634, 0.025], [4.0,  15.633, 0.015], [8.0,  14.097, 0.023],
                [9.0, 15.134, 0.018], [10.0, 15.247, 0.015]],
               [[4.0, 19.634, 0.025], [8.0,  10.097, 0.023], [10.0, 15.247, 0.015]],
               [[4.0, 13.633, 0.015], [8.0,  12.097, 0.023], [9.0,  15.134, 0.018]]]
common_values = [4.0,8.0] 

我试图抛出不包含公共ID号的元素。因此,将返回的是:

final_nested_list = [[[[4.0, 15.633, 0.015],[8.0, 14.097, 0.023]],[[4.0, 19.634, 0.025],
                    [8.0, 10.097, 0.023]], [[4.0, 13.633, 0.015],[8.0, 12.097, 0.023]]]

我在试图找出如何只遍历包含ID号的第一个元素时遇到了麻烦。

您可以使用嵌套列表理解:

>>> [[y for y in x if y[0] in common_values] for x in nested_list]
[[[4.0, 15.633, 0.015], [8.0, 14.097, 0.023]], [[4.0, 19.634, 0.025], [8.0, 10.097, 0.023]], [[4.0, 13.633, 0.015], [8.0, 12.097, 0.023]]]

如果common_values列表很大,那么最好先将其转换为集合,因为集合提供O(1)查找。

以上列表理解大致相当于:

>>> out_put = []
for x in nested_list:
   temp = []
   for y in x:
       if y[0] in common_values: #check if first item is present in common_keys
           temp.append(y)
   out_put.append(temp)
...    
>>> out_put
[[[4.0, 15.633, 0.015], [8.0, 14.097, 0.023]], [[4.0, 19.634, 0.025], [8.0, 10.097, 0.023]], [[4.0, 13.633, 0.015], [8.0, 12.097, 0.023]]]

嗨,我可以向你推荐两种方法之一:

使用任何函数检查嵌套列表中是否存在任何公共值

[[i for i in nl if any(j in i for j in common_values)] for nl in nested_list]

字符串查找集合的交集

cv_set = set(common_values)
[[i for i in nl if set(i) & cv_set] for nl in nested_list]

第一个是优选的,因为任何评估结果都使用较短的方式(直到第一个true语句)

最新更新