我正在尝试找到一个库,我可以使用该库来确定数字是否介于两个数字之间,或者是否必须使用for循环和if条件遍历每个数字
def get_numbers_in_between(li, x, y):
# x can be bigger than y or vice versa
if x > y:
big = x
small = y
else:
big = y
small = x
nums_in_between = [n for n in li if (n >= small and n <= big)]
return nums_in_between
print(get_numbers_in_between([9, 10, 11, 15, 19, 20, 21], 20, 10))
输出:
[10, 11, 15, 19, 20]
是否有一个图书馆会自动找出哪个更大或更小(x,y),然后将列表作为输入并返回一个新的列表,其中包含数字?
答案 0 :(得分:3)
如果您从给定的列表开始,并且需要提取满足条件的列表:
lst = [9, 10, 11, 15, 19, 20, 21]
print([n for n in lst if 10 <= n <= 20])
如果您需要所有整数,则只需
list(range(10, 20+1))
如果您需要首先对最大值和最小值进行排序,这是一个选择:
def get_numbers_in_between(li, x, y):
mx, mn = sorted((x, y))
return [n for n in li if mx <= n <= mn]
print(get_numbers_in_between(li=[9, 10, 11, 15, 19, 20, 21], x=20, y=10))
答案 1 :(得分:2)
您可以使用filter
,
>>> nums
[9, 10, 11, 15, 19, 20, 21]
>>> sorted_list = sorted(nums) # easier to find min, max ?
>>> min_, max_ = sorted_list[0], sorted_list[-1]
>>> filter(lambda x: min_ < x < max_, nums)
[10, 11, 15, 19, 20]
在itertools.ifilter
中有类似的python2
,
>>> import itertools
>>> list(itertools.ifilter(lambda x: 10 <= x <= 20, nums))
[10, 11, 15, 19, 20]
在itertools.filterfalse
的{{1}}中,
python3
答案 2 :(得分:2)
可以像建议的一样简单:
small = 8
big = 16
nums_in_between = [n for n in li if n in range(small, big)]
答案 3 :(得分:2)
尝试一下:
def get_numbers_in_between(l,x,y):
return [i for i in l if i in range(min(x,y), max(x,y)+1)]
get_numbers_in_between([9, 10, 11, 15, 19, 20, 21], 20, 10) # [10, 11, 15, 19, 20]
答案 4 :(得分:0)
在roganjosh的帮助下-很好!
dat=np.random.randint(0,20,50)
x=5
y=10
ans=dat[(dat>=x) & (dat<y)]
print(ans)
旧(在np.where):
import numpy as np
dat=np.random.randint(0,20,50)
x=5
y=10
ans=dat[np.where((dat>=x) & (dat<y))]
print(ans)
答案 5 :(得分:0)
OP :自动找出更大或更小的(x,y),然后将列表作为输入并返回包含数字的新列表?
通用方法:
def GetNumbersInBetween(lst, l_Bound, u_Bound):
n_List = []
lowerBound = min(l_Bound, u_Bound) # Get the lower val
upperBound = max(l_Bound, u_Bound) # Get the higher val
for x in lst:
if x >= lowerBound and x <= upperBound:
n_List.append(x)
return n_List
lst = [9, 10, 11, 15, 19, 20, 21]
lowerBound = 20 # intentionally given the wrong value
upperBound = 10 # intentionally given the wrong value
print(GetNumbersInBetween(lst, lowerBound, upperBound))
OR
使用list comprehension
:
print([x for x in lst if min(lowerBound,upperBound) <= x <= max(lowerBound,upperBound)])
输出:
[10, 11, 15, 19, 20]