我有一個陣列串列如下: Array =[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
示例:值 = 3、6、5、7、2、4、3、5、4、5、4、7、6、7、1、7、4、6、3
谷/峰 = v、p、v、p、v、p、v、p、v、p、v、p、v、p、v、p、v、p、v

uj5u.com熱心網友回復:
正如 Mark Ransom 和 SA.93 所建議的,python 中的索引從 0 開始。也許您對 R 更熟悉... :) 對于您的解決方案,試試這個;
def next_lowest_num(Array,num):
lst = []
for i in Array[Array.index(num):]:
if i >= num:
lst.append(i)
else:
lst.append(i)
break
return lst
print(next_lowest_num(Array=[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3],num=3))
print(next_lowest_num(Array=[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3],num=5))
# Output
[3, 6, 5, 7, 2]
[5, 7, 2]
希望這可以幫助...
uj5u.com熱心網友回復:
邏輯
分配索引開始
分配起始索引的值
從起始索引開始回圈到回圈結束
在回圈中檢查當前數字是否小于起始目標
切片串列以創建結果子串列
代碼
array = [3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
start_index = 0 # the index to start from
# start_index = int(input("Enter the index to start from: ")) # to take this a step further, you could ask the user for the index to start from
target = array[start_index] # the number in the starting index
for i in range(start_index, len(array)): # loop from the start index till the end
if array[i] < target: # if the current number is smaller than my traget
# split the list from the start index to the current index ( 1 because the slice is not inclusive)
print(array[start_index:i 1])
break
if i == len(array)-1: # if we reached the end of the list
print('fail') # print the rest of the list
輸入
start_index = 0
array = [3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
輸出
[3, 6, 5, 7, 2]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510101.html
標籤:Python算法窗户滑动
上一篇:TwoSum演算法(Python):重復元素的索引被視為相同
下一篇:排序到子字典?
