python - 检测列表是否在正值之后包含负值的 Pythonic 方法
问题描述
有没有更优雅的方法来检测列表中的值是负数,然后是正数?
例如[-1, 0, -2, 2]
,返回 True 为-1
负数,并且 的索引2
高于 的索引-1
。
[1, 2, 3, 2]
返回 False,因为所有值都是正数。
[-1, -2, -3, -4]
返回 False,因为所有值都是负数。
[4, 3, 2, 1, -1]
返回假。
到目前为止,这是我的代码:
def my_function(my_list):
neg_index = None
for index, item in enumerate(my_list):
if item < 0:
neg_index = index
if item > 0:
pos_index = index
if neg_index is not None:
if pos_index > neg_index:
return True
return False
解决方案
你可以使用itertools.groupby
:
from itertools import groupby
def positive_follows(lst):
# get a marker for a starting negative value
prev = False
for key, _ in groupby(lst, lambda x: x < 0):
# if a negative value is found, flip the marker
# and go to the next group
if key:
prev = key
continue
# If no marker was found, then we started at
# a positive value, so return False
if not prev:
return False
else:
# otherwise return True
return True
# If we only encounter negative values, then the for loop
# will complete and we should return False
else:
return False
x = [-1, 0, -2, 2] # True
assert positive_follows(x)
x = [1, 2, 3, 2] # False
assert not positive_follows(x)
x = [-1, -2, -3, -4] # False
assert not positive_follows(x)
推荐阅读
- ssl - HTTPS 的 GKE Ingress 和 TCP 的 LoadBalancer 在同一后端?
- python - 在 for 循环中向 Plotly Graph 添加跟踪,仅显示循环中的最后一个跟踪
- javascript - 当我使用列 lfor 分屏时,我看不到一些导航栏项目
- css - 等高的CSS网格线
- javascript - 为什么 IntersectionObserver 不适用于中间 div?
- c++ - 逆 Eigen::MatrixXd 的错误计算
- python - 没有函数python的分隔字符串字符
- reactjs - Carousel React JS、JSON、JSX TypeError:无法读取未定义的属性“”
- flutter - 颤振'未处理的异常:类型'列表
' 不是类型 'List 的子类型 ' - ddev - DDEV 项目使用 http 而不是 https 启动站点