问题
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]]
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],[]]
i.e. function should iterate all values in list a
and remove values such that 1 <= value <= 4
and 6 <= value <= 9
At present I have this :
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))
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
.
My output is [[2, 4, 5], [4, 5, 7, 9], [5], [2, 7, 9]]
whereas I want [[5],[5],[5],[]]
回答1:
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]
This returns:
[[5], [5], [5], []]
来源:https://stackoverflow.com/questions/52853641/remove-items-from-a-nested-list-based-on-comparing-values-obtained-from-another