我需要檢查一個數字是否存在的方法是一個串列/系列,如果它不回傳串列中的下一個最高數字。
例如:- 在串列中,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)
如果有一種方法可以用 pandas 資料框做到這一點,那就更好了。
uj5u.com熱心網友回復:
這是使用標準 Python 的一種方法(nums不需要排序):
def coerce_num(x):
return min((n for n in nums if n >= x), default=None)
>>> coerce_num(4)
5
>>> coerce_num(9)
20
(default=None在沒有數字大于 的情況下添加x)
uj5u.com熱心網友回復:
您可以使用遞回函式來實作這一點coerce_num(x 1),它將添加 1 并嘗試再次搜索。
方法一
nums = [1,2,3,5,7,8,20]
def coerce_num(x):
if x > max(nums):
return None
if x in nums:
return print("yes", x)
else:
coerce_num(x 1)
coerce_num(6)
方法二
nums = [1,2,3,9,7,8,20]
nums.sort()
def coerce_num(x):
for i in nums:
if x == i:
return print("yes", x)
if x < i:
return print("next highest", i)
uj5u.com熱心網友回復:
假設輸入串列在傳遞到下面的函式之前是預先排序的。
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))
uj5u.com熱心網友回復:
假設一個排序串列,bisect用于高效的二分搜索:
import bisect
nums = [1,2,3,5,7,8,20]
def coerce_num(nums, x):
return x[bisect.bisect_left(x, nums)]
coerce_num(8, nums)
# 8
coerce_num(20, nums)
# 20
coerce_num(0, nums)
# 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522488.html
上一篇:試圖拆分數字但串列索引超出范圍
