问题描述:
Not all of the elements are important. What you need to do here is to remove from the list all of the elements before the given one.
For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove all elements that go before 3 - which is 1 and 2.
We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn't be changed. (如果找不到切割元素,则不应更改列表) (2) if the list is empty, then it should remain empty.(如果列表为空,则应保持为空)
Input: List and the border element.
Output: Iterable (tuple, list, iterator ...).
from typing import Iterable
def remove_all_before(items: list, border: int) -> Iterable:
# your code here
return items
if __name__ == '__main__':
print("Example:")
print(list(remove_all_before([1, 2, 3, 4, 5], 3)))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(remove_all_before([1, 2, 3, 4, 5], 3)) == [3, 4, 5]
assert list(remove_all_before([1, 1, 2, 2, 3, 3], 2)) == [2, 2, 3, 3]
assert list(remove_all_before([1, 1, 2, 4, 2, 3, 4], 2)) == [2, 4, 2, 3, 4]
assert list(remove_all_before([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7]
assert list(remove_all_before([], 0)) == []
assert list(remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7, 7, 7, 7, 7, 7, 7, 7, 7]
print("Coding complete? Click 'Check' to earn cool rewards!")
思路:
先在列表中找到边界条件(索引),然后输出边界条件之后的所有元素;然后如果是空列表或者没有找到边界条件,就返回原列表。
from typing import Iterable
def remove_all_before(items: list, border: int) -> Iterable:
# your code here
if border in items:
border=items.index(border) #找到边界条件的索引值
return items[border:] #返回索引值开始往后的所有元素组成的列表
else:
return items
或者直接写成一行:
return items[items.index(border):] if border in items else items
或者不用if,试试try和expect:
from typing import Iterable
def remove_all_before(items: list, border: int) -> Iterable:
# your code here
try: return items[items.index(border):]
except: return items
异常处理
捕捉异常可以使用try/except语句。
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
如果你不想在异常发生时结束你的程序,只需在try里捕获它。