我需要检查一个数字是否存在的方法是一个列表/序列,如果它没有返回列表中的下一个最高的数字。
例如:-在列表nums = [1,2,3,5,7,8,20]中,如果要输入数字4,则函数将返回5,而> 8 < 20则返回20,依此类推。
下面是这个前提的一个非常基本的例子:
nums = [1,2,3,5,7,8,20]
def coerce_num(x):
if x in nums:
return print("yes")
else:
return ("next number in list")
coerce_num(9)如果有办法处理熊猫的数据,那就更好了。
发布于 2022-10-27 21:06:38
假设输入列表在传递到下面的函数之前是预先排序的。
import numpy as np
def check_num(list_of_nums, check):
# use list comprehension to find values <= check
mask=[num <= check for num in list_of_nums]
# find max index
maxind = np.max(np.argwhere(mask))
# if index is last num in list then return last num (prevents error)
# otherwise, give the next num
if maxind==len(list_of_nums)-1:
return list_of_nums[-1]
else:
return list_of_nums[maxind+1]
nums = [1,2,3,5,7,8,20]
print(check_num(nums, 6))https://stackoverflow.com/questions/74227665
复制相似问题