首页 > 解决方案 > 检测列表是否在正值之后包含负值的 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

标签: pythonlist

解决方案


你可以使用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)

推荐阅读