Python - 如果数组在其他数组的范围内

Python - If array is in range of other array

含义"if each item is within range of other item with the same index"。

price = [1, 2]  
budget = [5, 7]

这个有效:

if price[0] in range(budget[0]) and price[1] in range(budget[1]):
    affordable = True

我认为有一些方法可以只引用整个数组。像这样:if price in budget:

您可以使用:

if all(x in range(y) for x,y in zip(price,budget)):
    affordable = True

这将创建 price[i],budget[i] 的元组,然后对于这些元组中的每一个,我们检查 price[i] 是否在 range(budget[i]) 中。不过,您可以将其进一步优化为:

if all(<b>0 <= x < y</b> for x,y in zip(price,budget)):
    affordable = True

请注意,这假设 price 所有 整数。但是,如果您使用 x in range(y) 如果 x 不是整数,它将失败。所以 0.7 in range(10) 会失败,而我们的第二种方法会成功(但这当然取决于你想要什么)。

假设价格和预算都必须是 non-negative,使用 in range 似乎是 over-complicating 的事情。相反,您可以只使用 < 运算符。

无论您使用 < 还是 in range,最简单的方法似乎是 zip 两个列表并在对上应用条件:

if (all([x[0] >= x[1] for x in zip(budget, price)])):
    affordable = True