Python识别数字在哪个区间 [英] Python identify in which interval the numbers are
问题描述
我想为Python中的循环运行一个循环,该循环检查循环中的每个元素的给定间隔的时间间隔。例如:
I would like to run a for
loop in Python that checks, given a certain amount of intervals, for each element of the loop, in which interval it is. For instance:
interval_1 = [1; 10]
interval_2 = [11; 58]
我正在寻找比大型更优雅的解决方案if / elif / else
条件,例如我的想法是加载一个包含 n
对应于间隔末端的数字的excel工作表,并使用函数我发现我的号码在哪个区间。
I was looking for a more elegant solution than a large if/elif/else
condition, for instance my idea was to load an excel worksheet containing n
couples of numbers corresponding to the interval extremities, and use a function that finds me for in which interval my number is.
Python中是否存在类似的函数?或者最终如何做到这一点?
Does a similar function exist in Python? Or eventually how could this be done?
推荐答案
numpy
has nice support for this without having to write a for
loop:
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:
If you insist on a for
loop, just iterate over the elements to bin, and the bins:
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))
指定垃圾箱范围(如你的例子),但这并不是技术上必要的(例如 numpy
代码)。您可以仅存储临界值并比较 cutoffs [: - 1]
中的相邻元素。
The above uses tuples to specify the bin ranges (like your example), but that's not technically necessary (e.g. the numpy
code). You could store just the cutoffs and compare adjacent elements from cutoffs[:-1]
.
这篇关于Python识别数字在哪个区间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!