我正在尝试查找每个正值序列的起始位置的索引。我只在代码中得到了正值的位置。我的代码如下:
this.state = {
barChart: {
options: {
plotOptions: {
xaxis: {
categories: []
}}}
series: [{name: [], data: []}}
我希望[-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]
答案 0 :(得分:0)
当前您选择的是数字为正的所有索引,相反,您只想在数字从负转换为正时才收集索引。
此外,您还可以处理所有负数,也可以处理从正数开始的数字
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]
答案 1 :(得分:0)
我认为如果您使用列表理解
会更好index = [i for i, x in enumerate(lst) if x > 0]