简体   繁体   中英

Python : Remove all values from a list in between two values

I have a list of string values.

list1 = ["13:00","13:10","13:20","13:30","13:40"]
range_start = "13:10"
range_end = "13:30"

I want to remove all values (including range_start and range_end)that lie in between the ranges.

EDIT:

Sorry, misread your question. I thought you only wanted to keep these values. Changed my code accordingly.

list1 = ["13:00","13:10","13:20","13:30","13:40"]
range_start = "13:10"
range_end = "13:30"

You can use list comprehension with the range condition:

list1 = [x for x in list1 if not(range_start<=x<=range_end)]
print(list1)

You could also use filter on your list:

list1=list(filter(lambda x:not(range_start<=x<=range_end), list1))
print(list1)

To remove the ends of the list, you can do this:

list1 = ["13:00","13:10","13:20","13:30","13:40"]
del list1[1:-1]
print(list1)

the result is this:

['13:00', '13:40']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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