简体   繁体   English

从 Python 范围之间的列表中删除项目

[英]Remove items from a list between ranges in Python

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:输入应具有以下结构,但让我指出第一个和最后一个列表应该是灵活的,它们的长度并不总是为 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:从我的初始列表中,我需要删除值 3 和 5 之间的项目以及值 9 和 13 之间的项目,所以我的最终结果是:

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,谢谢和问候,

You can build the range objects, for all the corresponding elements from first and last , like this您可以为firstlast的所有相应元素构建范围对象,如下所示

>>> 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)

You almost had it.你几乎拥有它。 Just unindent the else to where it belongs, remove the bad break , and make the comparisons inclusive:只需将else缩进它所属的位置,删除坏的break ,并进行比较:

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)

Try it online! 在线尝试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM