繁体   English   中英

从 python 的列表中查找下一个最小数字

[英]Finding a next lowest number from a List in python

我有一个 arrays 列表如下: Array =[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]

我想打印从第一个给定数字到 self 之后的下一个最低数字的范围。

示例:数组 =[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3] 给定索引 0 中的数字 3 作为一个起始编号。

让我们从索引 0 开始,其值为 3,其后的最小值是索引 4,值为 2 即子数组 = [3, 6, 5, 7, 2]

示例 2 让我们选择 5 作为下一个数字,然后下一个最小的数字看起来像这个子数组 = [5, 7, 2]

这样我就可以从子阵列中获得最高峰值数。

正如 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]

希望这可以帮助...

逻辑

分配索引开始

分配起始索引的值

从起始索引开始循环到循环结束

在循环中检查当前数字是否小于起始目标

切片列表以创建结果子列表

代码

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]

output

[3, 6, 5, 7, 2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM