在给定列表中,如何确定跟随较大数字的较小数字? (蟒蛇)

时间:2020-08-12 10:41:45

标签: python python-3.x

例如,给您一个列表,说: a = [14, 26, 30, 15, 25, 30]

小数字后面有大数字是15。所以我只想打印15。

我在这里:

def alist(a):
    for i in a:
        if i ???

帮助,我迷路了。

3 个答案:

答案 0 :(得分:0)

如果您为循环中的每个项目存储了最后一个数字,则可以回头查看它。

首先存储列表中的第一个数字。循环之后的数字(使用python数组切片a[1:])。

如果当前数字小于最后一个数字<,则打印出来。

始终将当前号码存储在最后一个号码中。

答案 1 :(得分:0)

使用for循环会慢很多,最好使用NumPy,如下:

import numpy as np
a = [14, 26, 30, 15, 25, 30]
a = np.array(a)
greater_num = a[np.append(False, (a[1:]-a[:-1])<0)]
print(greater_num)

# Output: array([15])

答案 2 :(得分:0)

您可以像这样简单地做到这一点,而无需使用for循环-

a = [14, 26, 30, 15, 25, 30]
s = set(a) # This is required if you have duplicate elements in your list, will convert list into sets and remove duplicates
print (sorted(s)[1]) # print the second smallest number.

输入量:15

您也可以使用heapq

import heapq
a = [14, 26, 30, 15, 25, 30]
print (heapq.nsmallest(2, a)[-1]) # print the second smallest number.

输入量:15

相关问题