[英]python function to determine how statistically likely it is that a number belongs to a given list of numbers
[英]In a given list, how to determine the small number that followed a bigger number? (Python)
例如,给你一个列表说: a = [14, 26, 30, 15, 25, 30]
大数字前面的小数字是 15。所以我只想打印数字 15。
这是我所在的位置:
def alist(a):
for i in a:
if i ???
救命,我迷路了。
如果您存储循环中每个项目的最后一个数字,您可以回头检查它。
首先存储列表中的第一个数字。 之后循环数字(使用 python 数组切片a[1:]
)。
如果当前数字小于<
最后一个数字,则打印它。
始终将当前号码存储在最后一个号码中。
使用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])
您可以简单地这样做,而无需使用 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.