我想在 Python 中运行一个 for
循环,在给定一定量的间隔的情况下,检查循环的每个元素所在的间隔。例如:
interval_1 = [1; 10]
interval_2 = [11; 58]
我一直在寻找比大型 if/elif/else
条件更优雅的解决方案,例如我的想法是加载包含 n
组数字的 Excel 工作表对应于区间四肢,并使用一个函数来查找我的号码所在的区间。
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
循环,只需迭代到 bin 的元素,以及 bin:
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识别数字在哪个区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36479374/