I am trying to remove some items from a list. Those items to be removed are defined by different ranges given by two lists that define the start and end of the ranges.
The inputs shall have the following structure but let me point out that the first & last list shall be flexible, not always their lengths are going to be 2:
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
first = [3,9]
last = [5,13]
From my initial list, I need to remove items between values 3 & 5 and items between values 9 & 13 so my final outcome would be:
lst = [0,1,2,6,7,8,14,15]
Let me post what I´ve done so far with no success:
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
first = [3,9]
last = [5,13]
lst = []
for i in list:
for j, k in zip(first, last):
if i > j and i < k:
break
else:
lst.append(i)
break
print(lst)
Thank you and regards,
CodePudding user response:
You can build the range objects, for all the corresponding elements from first
and last
, like this
>>> ranges = [range(start, end 1) for start, end in zip(first, last)]
then just check if the current number does not fall under any of the ranges. This is possible as the range objects allow us to query if a particular number is within the range or not.
>>> [num for num in list if all(num not in rng for rng in ranges)]
[0, 1, 2, 6, 7, 8, 14, 15]
In your code, you have to check all the ranges to see if the current number is not there in any of them. Only if the current number satisfies that, it should be included in the result.
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
first = [3, 9]
last = [5, 13]
result = []
for current_num in list:
found_matching_range = False
for start, end in zip(first, last):
if start <= current_num <= end: # Note the `=`. Inclusive comparison
found_matching_range = True
break
if not found_matching_range:
result.append(current_num)
print(result)
CodePudding user response:
You almost had it. Just unindent the else
to where it belongs, remove the bad break
, and make the comparisons inclusive:
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
first = [3,9]
last = [5,13]
lst = []
for i in list:
for j, k in zip(first, last):
if i >= j and i <= k:
break
else:
lst.append(i)
print(lst)