一个很酷的解决方案是使用标准库 Itertools!
from itertools import filterfalse
list = [-550, -455, -355, -215, -195, 500, 645, 800, 975]
def get_pos_neg(lst):
result = filterfalse(lambda x: x<0 , lst)
positive_value = list.index(next(result))
neg = list[positive_value-1]
negative_value = list.index(neg)
return [negative_value, positive_value]
print(get_pos_neg(list)) # [4, 5]
编辑:正如@Mark Meyer 指出的那样,takewhile 和dropwhile 将在满足条件时运行,因此我先进行了检查。仅用于演示如何利用 itertools 模块,可能有更有效的方法来实现这一点。
from itertools import takewhile, dropwhile
list = [-550, -455, -355, -215, -195, 500, 645, 800, 975]
list_pos = [-195, 500, 645, 800, 975, -550, -455, -355, -215]
def get_pos_neg(lst):
if lst[0] < 0:
negative = [n for n in takewhile(lambda x: x<0, lst)]
positive = [n for n in dropwhile(lambda x: x<0, lst)]
polar_change = [list.index(negative[-1]), list.index(positive[0])]
return polar_change
else:
negative = [n for n in takewhile(lambda x: x > 0, lst)]
positive = [n for n in dropwhile(lambda x: x > 0, lst)]
polar_change = [list.index(negative[-1]), list.index(positive[0])]
return polar_change
start_neg = get_pos_neg(list)
star_pos = get_pos_neg(list_pos)
print(start_neg) # [4, 5]
print(star_pos) # [4, 5]