如何从嵌套列表中的元素中删除非常见值?

时间:2013-06-27 19:47:24

标签: python unique nested-lists

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

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

ID#,Magnitude和Magnitude Error都是浮点数。我还有一个公共ID号列表。我想要做的是删除标记有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号的第一个元素时遇到了麻烦。

2 个答案:

答案 0 :(得分:1)

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

>>> [[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]]]

答案 1 :(得分:1)

您好我可以向您推荐两种方法之一:

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

[[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]

首先是优选的,因为任何使用较短的方式(直到第一个真实的陈述)评估结果