关于python:从列表中删除项目范围

Removing range of items from a list

是否有方法删除列表中范围内的项目?例如:a = [1,2,3,4,5]。如何从3到5删除项目?


像这样的东西就可以了

1
2
3
4
5
[z for z in [1,2,3,4,5,6,7] if not 3<=z<=5]


Out[2]:
[1, 2, 6, 7]

如果你想让它更灵活,可以根据你的需要用变量替换,这很简单:

1
2
3
4
5
alist=[1,2,3,4,5,6,7]
lowerbound=3
upperbound=5
resultlist=[z for z in alist if not lowerbound<=z<=upperbound]
#result you want stored as 'resultlist'


是的,您可以使用列表理解来过滤数据。

1
2
a = [1,2,3,4,5]
print([x for x in a if 3 <= x <= 5])