猿问

如何将浮点数与其组成部分是 Python 中的间隔的数组进行比较?

我想将数组:[2, 4, 6, 9] 与间隔矩阵 (m*n) 进行比较:


[[0,1], [0,1], [0,1], [0,1]

 [1,2], [1,2], [1,2], [1,2]

   .      .      .      .

   .      .      .      . 

   .      .      .      . ]

如果数字不在该区间内,则结果将是一个矩阵 (m*n),其中 0 或在其他情况下为 1。


白猪掌柜的
浏览 243回答 3
3回答

慕莱坞森

一种方法是使用嵌套列表理解data = [[0, 1], [0, 1], [1, 2], [1, 5], [5, 10], [11, 20]]check = [2, 4, 6, 9]result = [any(1 if l <= y <= r else 0 for y in check) for l, r in data]# [False, False, True, True, True, False]如果您想要 0 或 1,您可以使用以下result = [max(1 if l <= y <= r else 0 for y in check) for l, r in data]# [0, 0, 1, 1, 1, 0]

慕后森

由于您的范围是隐式排序的,您可以简单地检查您的数字是否在开始元素和停止元素之间:for each element, e, in your input vector:&nbsp; &nbsp; for each range pair (low, high) in your interval matrix:&nbsp; &nbsp; &nbsp; &nbsp; if low <= e <= high; then&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; true&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; false在 Python 中:def check_within_range(arr, mat):&nbsp; &nbsp; return [[low <= e <= high for e in arr] for (low, high) in mat]

守着星空守着你

这应该返回一个布尔值矩阵(可以很容易地将其视为 1 和 0)。希望这是您想要实现的目标。# m is the matrix# a is the arrayresult = [[y in range(x[0], x[-1]) for y in a] for x in m]
随时随地看视频慕课网APP

相关分类

Python
我要回答