使用列表推导排除列表中处于一定范围内的项目 [英] Excluding items from a list that are in a certain range using list comprehension
本文介绍了使用列表推导排除列表中处于一定范围内的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表:a = [10.0,20.0]
和b = [1.0,10.0,15.0,20.0,30.0,100.0]
.
如何从列表b
中删除10.0
和20.0
之间的所有元素?这是我尝试过的:
I have two lists: a = [10.0,20.0]
and b = [1.0,10.0,15.0,20.0,30.0,100.0]
.
How can I remove from list b
all the elements between 10.0
and 20.0
? Here is what I tried:
c = [b[y] for y in range(len(b)) if (b[y] < a[0] or b[y] > a[1])]
我希望得到c = [1.0, 30.0, 100.0]
,但是我得到c = [1.0,10.0,15.0,20.0,30.0,100.0]
.
I expect to get c = [1.0, 30.0, 100.0]
, but I get c = [1.0,10.0,15.0,20.0,30.0,100.0]
.
如何仅通过列表理解来排除列表中特定范围内的组件?
How can I exclude components from a list that are in a certain range by using only list comprehension?
推荐答案
您可以通过直接迭代b
的元素来简化操作,但是您的原始代码也适用于我:
You can simplify by iterating b
's elements directly, but your original code works for me, too:
a = [10.0, 20.0]
b = [1.0, 10.0, 15.0, 20.0, 30.0, 100.0]
c = [x for x in b if x < a[0] or x > a[1]]
# [1.0, 30.0, 100.0]
# Your version:
c = [b[y] for y in range(len(b)) if (b[y] < a[0] or b[y] > a[1])]
# [1.0, 30.0, 100.0]
这篇关于使用列表推导排除列表中处于一定范围内的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文