根据比较从另一个嵌套列表中获得的值,从嵌套列表中删除项目 [英] Remove items from a nested list based on comparing values obtained from another nested list
问题描述
我有两个嵌套列表,形式:
I have two nested lists in the form:
a = [[1,2,3,4,5],[3,4,5,6,7,8,9],[5],[1,2,3,6,7,8,9]]
b = [[1,4],[6,9]]
我想要一个将接收这两个列表的函数,使用列表b
的每个子列表中的值,并使用该函数删除列表a
中的值,以便输出看起来像这样:
I want a function that will take these two lists, use the values in each sublist of list b
and use that to delete values in list a
so that the output looks like this :
[[5],[5],[5],[]]
即函数应迭代列表a
中的所有值,并删除诸如1 <= value <= 4
和6 <= value <= 9
i.e. function should iterate all values in list a
and remove values such that 1 <= value <= 4
and 6 <= value <= 9
目前我有这个:
def remove_unnecessary_peaks(peaks_total,peaks_to_be_excluded):
redacted_peak_list = peaks_total.copy()
i=0
for item in peaks_total:
for value_set in peaks_to_be_excluded:
for peak in item:
#print (value_set[0],peak,value_set[1])
if value_set[0]<=peak<=value_set[1]:
redacted_peak_list[i].remove(peak)
i=i+1
return (redacted_peak_list)
a = [[1,2,3,4,5],[3,4,5,6,7,8,9],[5],[1,2,3,6,7,8,9]]
b = [[1,4],[6,9]]
print(remove_unnecessary_peaks(a,b))
我已经通过执行redacted_peak_list = peaks_total.copy()
来制作了数据的副本,这样我就不会修改peaks_total
变量,因为它会破坏索引编制.在Spyder的调试模式下,我看到变量peak
没有正确索引,我看到它跳过了子列表a
中的数字.
I have made a copy of the data by doing redacted_peak_list = peaks_total.copy()
so that I don't modify the peaks_total
variable as it will screw up the indexing. In Spyder's debug mode I see that the variable peak
is not being indexed properly, I see it skipping numbers from sublist a
.
我的输出是[[2, 4, 5], [4, 5, 7, 9], [5], [2, 7, 9]]
,而我想要的是[[5],[5],[5],[]]
My output is [[2, 4, 5], [4, 5, 7, 9], [5], [2, 7, 9]]
whereas I want [[5],[5],[5],[]]
推荐答案
您可以使用如下列表理解:
You can use a list comprehension like this:
[[i for i in s if not any(l <= i <= h for l, h in b)] for s in a]
这将返回:
[[5], [5], [5], []]
这篇关于根据比较从另一个嵌套列表中获得的值,从嵌套列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!