在while循环中,无法从列表中排除特定范围内的项目 [英] Unable to exclude items from a list, in a while loop, that are in a certain range
使用香草python,您可以使用any
/all
进行概括.我要和any
一起去.
>>> [x for x in b if not any(i <= x <= j for i, j in zip(a[::2], a[1::2]))]
[1.0, 100.0]
此zip
每隔一对带有zip
的列表项,并逐个检查以确保x
不在其中.
如果您对表演感兴趣,请考虑使用熊猫方法.您可以针对该任务构建Intervalindex
.搜索是对数的,并且速度非常快.
>>> import pandas as pd
>>> idx = pd.IntervalIndex.from_arrays(a[::2], a[1::2], closed='both')
>>> [x for x, y in zip(b, idx.get_indexer(b)) if y == -1]
[1.0, 100.0]
So I posted a question before, but it was too simplified and rightly got flagged as a duplicate. I'm now posting my problem in more detail so my issue might, hopefully, be resolved. Briefly it is as follows:
I have two lists: a = [10.0,20.0,25.0,40.0]
and b = [1.0,10.0,15.0,20.0,30.0,100.0]
Using list comprehension, I want to exclude from b the ranges of elements specified in a. That is: remove from b all elements between 10.0 and 20.0, and between 25.0 and 40.0. Here is what I tried:
kk = 0
while kk < len(a):
up_lim = a[kk] #upper limit
dwn_lim = a[kk+1] #lower limit
x = [b[y] for y in range(len(b)) if (b[y]<dwn_lim or b[y]>up_lim)] #This line produces correct result if done outside of a while loop. Somehow fails in while loop.
b = list(x) #update the old list with the new&reduced list
kk += 2 #update counter
I'm expecting the result x = [1.0,100.0]
, but I get x = [1.0,10.0,15.0,20.0,30.0,100.0]
In fact, the key line with the list comprehension works if I do it outside the while loop (of course this is useless because list 'a' could be arbitrary in size which is why I used a while loop).
So the question is: how and why does a while loop stop the list comprehension from happening correctly?
With vanilla python, you can generalise using any
/all
. I'm going with any
here.
>>> [x for x in b if not any(i <= x <= j for i, j in zip(a[::2], a[1::2]))]
[1.0, 100.0]
This zip
s every alternate pair of list items with zip
, and one by one check to ensure that x
is not in any of them.
If you're interested in a performance, consider a pandas approach. You can build an Intervalindex
, right for the task. Searching is logarithmic, and very fast.
>>> import pandas as pd
>>> idx = pd.IntervalIndex.from_arrays(a[::2], a[1::2], closed='both')
>>> [x for x, y in zip(b, idx.get_indexer(b)) if y == -1]
[1.0, 100.0]
这篇关于在while循环中,无法从列表中排除特定范围内的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!