在列表中找到第一个正元素的索引-Python

邓比

我试图找到每个正值序列的起始位置的索引。我只在代码中得到了正值的位置。我的代码如下:

index = []
for i, x in enumerate(lst):
  if x > 0:
    index.append(i)
print index

我预计[-1.1、2.0、3.0、4.0、5.0,-2.0,-3.0,-4.0、5.5、6.6、7.7、8.8、9.9]的输出为[1、8]

Devesh库玛·辛格

当前,您正在选择数字为正的所有索引,相反,您只想在数字从负转换为正时才收集索引。

另外,您可以处理所有负数,也可以处理从正数开始的数

def get_pos_indexes(lst):

    index = []

    #Iterate over the list using indexes
    for i in range(len(lst)-1):

        #If first element was positive, add 0 as index
        if i == 0:
            if lst[i] > 0:
                index.append(0)
        #If successive values are negative and positive, i.e indexes switch over, collect the positive index
        if lst[i] < 0 and lst[i+1] > 0:
            index.append(i+1)

    #If index list was empty, all negative characters were encountered, hence add -1 to index
    if len(index) == 0:
        index = [-1]

    return index

print(get_pos_indexes([-1.1, 2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
print(get_pos_indexes([2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
print(get_pos_indexes([2.0,1.0,4.0,5.0]))
print(get_pos_indexes([-2.0,-1.0,-4.0,-5.0]))

输出将是

[1, 8]
[0, 7]
[0]
[-1]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在列表python中找到第二个元素和第一个元素的差异

在整数列表中找到第一个唯一元素:python

Python:在符合给定条件的第一个对象列表中找到位置

Python在列表中找到非零数字的第一个实例

在Python中找到单词的第一个元音

如何从链表中找到第一个索引,在 Python 中使用递归找到某个值

获取 Python 列表列表中第一个元素的索引

如何在 python 列表中找到下一个非 NaN 元素的索引

Python:返回列表的第一个元素的索引,使传递的函数为true

第一个Python列表索引大于x?

Python如何通过知道列表中列表的第一个元素来获取列表中列表的索引?

Python,第一个列表索引-上一个列表索引,然后打印

如何找到包含想要的值的列表(在列表中)的第一个实例的索引(在Python中)?

Python:嵌套列表中的第一个元素

遍历Python列表,但第一个元素在末尾?

更改每组 Python 列表的第一个元素

用python中元组列表中元组的第一个元素索引元素的最快方法

在python中找到第一个数字是元组

Selenium / Python:为什么在我的for循环迭代中找到第一个元素后,为什么Selenium find_element_不再通过查找元素了?

如何在Python列表中找到元素[-1]的正索引

成对浏览一个列表,除了第一个元素,Python

Python在索引后找到字符的第一个出现

Python-如何替换列表列表中每个列表的第一个元素

匹配python中两个列表列表之间的第一个元素

Python 连接两个列表,第一个索引相同

迭代Python列表中的连续元素,以使最后一个元素与第一个元素结合

当第一个元素大于下一个元素时,减去列表中的连续元素-Python

删除列表元素,直到到达Python中的第一个空元素

如何从python列表中的每个列表中拉出第一个元素?