所以我发了一个问题before https://stackoverflow.com/questions/48255911/excluding-items-from-a-list-that-are-in-a-certain-range-using-list-comprehension,但它太简单了,正确地被标记为重复。我现在更详细地发布我的问题,以便我的问题有望得到解决。简单来说如下:
我有两个清单:a = [10.0,20.0,25.0,40.0]
且 b =[1.0,10.0,15.0,20.0,30.0,100.0]
使用列表理解,我想从 b 中排除 a 中指定的元素范围。即:从b中移除10.0到20.0之间、25.0到40.0之间的所有元素。这是我尝试过的:
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
我期待结果x = [1.0,100.0]
,但我得到x = [1.0,10.0,15.0,20.0,30.0,100.0]
事实上,如果我在 while 循环之外执行此操作,则列表理解的关键行会起作用(当然这是无用的,因为列表“a”的大小可以是任意的,这就是我使用 while 循环的原因)。
所以问题是: while 循环如何以及为何阻止列表理解正确发生?