Python 确定数字在哪个区间
Python identify in which interval the numbers are
我想在 Python 中 运行 一个 for
循环,在给定一定间隔的情况下,检查循环的每个元素在哪个间隔中。例如:
interval_1 = [1; 10]
interval_2 = [11; 58]
我一直在寻找比大型 if/elif/else
条件更优雅的解决方案,例如我的想法是加载一个 excel 工作表,其中包含对应于间隔的 n
对数字四肢,并使用一个函数来查找我的号码所在的时间间隔。
Python中是否存在类似的功能?或者最终如何做到这一点?
numpy
has nice support for this 无需编写 for
循环:
import numpy as np
data = np.array([0.2, 6.4, 3.0, 1.6])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
cats = np.digitize(data, bins)
cats
# array([1, 4, 3, 2])
如果您坚持 for
循环,只需遍历要分箱的元素,分箱:
data = [0.2, 6.4, 3.0]
bins = [(0.0, 1.0), (1.0, 4.0), (4.0, 10.0)] # assumed (lower, upper] format
cats = []
for elem in data:
for idx, bounds in enumerate(bins, start=1):
if bounds[0] < elem <= bounds[1]:
cats.append(idx)
break
else:
raise ValueError('No bin for {}'.format(elem))
上面使用元组来指定 bin 范围(如您的示例),但这在技术上不是必需的(例如 numpy
代码)。您可以只存储截止值并比较来自 cutoffs[:-1]
.
的相邻元素
如果您有一个非常大的范围列表,这里的解决方案应该 运行 更快。它使用python的bisect
模块做一个binary search来快速找到物品所属的范围。
对于这个例子,我使用的范围是 2..5、7..9 和 13..13。
该代码检查是否所有从 0 到 14 的数字都在提供的范围之一内。
代码:
from bisect import *
ranges = [2, 5, 7, 9, 13, 13] # Using this convention: 2..5, 7..9, 13..13. Assume ranges inclusive.
for item in range(15):
valid = False
L = (bisect_left(ranges, item) // 2) * 2
if L+1 < len(ranges):
valid = ranges[L] <= item and ranges[L + 1] >= item
print(item, valid)
输出:
0 False
1 False
2 True
3 True
4 True
5 True
6 False
7 True
8 True
9 True
10 False
11 False
12 False
13 True
14 False
我想在 Python 中 运行 一个 for
循环,在给定一定间隔的情况下,检查循环的每个元素在哪个间隔中。例如:
interval_1 = [1; 10]
interval_2 = [11; 58]
我一直在寻找比大型 if/elif/else
条件更优雅的解决方案,例如我的想法是加载一个 excel 工作表,其中包含对应于间隔的 n
对数字四肢,并使用一个函数来查找我的号码所在的时间间隔。
Python中是否存在类似的功能?或者最终如何做到这一点?
numpy
has nice support for this 无需编写 for
循环:
import numpy as np
data = np.array([0.2, 6.4, 3.0, 1.6])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
cats = np.digitize(data, bins)
cats
# array([1, 4, 3, 2])
如果您坚持 for
循环,只需遍历要分箱的元素,分箱:
data = [0.2, 6.4, 3.0]
bins = [(0.0, 1.0), (1.0, 4.0), (4.0, 10.0)] # assumed (lower, upper] format
cats = []
for elem in data:
for idx, bounds in enumerate(bins, start=1):
if bounds[0] < elem <= bounds[1]:
cats.append(idx)
break
else:
raise ValueError('No bin for {}'.format(elem))
上面使用元组来指定 bin 范围(如您的示例),但这在技术上不是必需的(例如 numpy
代码)。您可以只存储截止值并比较来自 cutoffs[:-1]
.
如果您有一个非常大的范围列表,这里的解决方案应该 运行 更快。它使用python的bisect
模块做一个binary search来快速找到物品所属的范围。
对于这个例子,我使用的范围是 2..5、7..9 和 13..13。
该代码检查是否所有从 0 到 14 的数字都在提供的范围之一内。
代码:
from bisect import *
ranges = [2, 5, 7, 9, 13, 13] # Using this convention: 2..5, 7..9, 13..13. Assume ranges inclusive.
for item in range(15):
valid = False
L = (bisect_left(ranges, item) // 2) * 2
if L+1 < len(ranges):
valid = ranges[L] <= item and ranges[L + 1] >= item
print(item, valid)
输出:
0 False
1 False
2 True
3 True
4 True
5 True
6 False
7 True
8 True
9 True
10 False
11 False
12 False
13 True
14 False