【问题标题】:Find index of consecutive values in a list, if from negative values goes to positive using Python如果使用 Python 从负值变为正值,则在列表中查找连续值的索引
【发布时间】:2020-12-22 19:23:23
【问题描述】:

我有一个这样的 python 列表:

List = [-550, -455, -355, -215, -195, 500, 645, 800, 975]

我想检查 List 中的两个连续值,如果来自 negative 的值变为 positive 并打印这些值的 索引,如下所示:

结果:

index=[4,5]

【问题讨论】:

  • 只有一个这样的索引吗?换句话说,数据是否排序?
  • 那么next([i-1, i] for i, n in enumerate(List) if n >= 0) 就可以了。

标签: python list indexing itertools


【解决方案1】:

这是一个简单明了的循环。

for i in range(0, len(List)-1):
    if List[i] < 0 and List[i + 1] > 0:
        print(i, i + 1)

作为一个新的贡献者,一些建议:考虑练习编写具有多个循环不变量的基本循环。

【讨论】:

    【解决方案2】:

    您可以将列表自身压缩到一个偏移量,例如:

    zip(l, l[1:])
    

    这将创建如下对:

    [(-550, -455)...]
    

    如果您 enumerate() 获取索引,则可以过滤第一个元素为负数且第二个元素为正数的情况:

    l = [-550.0, -455.0, -355.0, -215.0, -195.0, 500.0, 645.0, 800.0, 975.0, 1265.0, 1370.0, 1615.0, 1615.0, 1615.0, 1615.0]
    
    [[idx, idx+1] for idx, [a, b] in enumerate(zip(l, l[1:])) if a < 0 < b]
    # evaluates to [[4, 5]]
    

    【讨论】:

    • 我对你所指出的做了一个幼稚的捕捉,我可能认为一个更好的方法来实现这一点,我的意思只是演示非常强大的 itertools 模块
    • 这是一个很好的答案@FedericoBaù,指出 itertools 的用处是多么有用。
    【解决方案3】:

    一个很酷的解决方案是使用标准库 Itertools!

    1。 filterfalse

    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]
    

    2.takewhile & dropwhile

    编辑:正如@Mark Meyer 指出的那样,takewhiledropwhile 将在满足条件时运行,因此我先进行了检查。仅用于演示如何利用 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      相关资源
      最近更新 更多