[英]Python: Check is each value is between/equal to 0 to 3 in the tuple?
[英]Check if value is between pair of values in a tuple?
是否有一種有效的方法(很好的語法)來檢查值是否在元組中包含的兩個值之間?
我能想到的最好的事情是:
t = (1, 2)
val = 1.5
if t[0] <= val <= t[1]:
# do something
是否有更好的方法來編寫條件?
不,沒有專門的語法,使用鏈式比較是正確的方法。
我能提供的“精確”是首先使用元組解包,但這只是可讀性結冰:
low, high = t
if low <= val <= high:
如果您正在使用collection.namedtuple()
生成的元組子類,您當然也可以使用以下屬性:
from collections import namedtuple
range_tuple = namedtuple('range_tuple', 'low high')
t = range_tuple(1, 2)
if t.low <= val <= t.high:
你可以制作自己的糖:
class MyTuple(tuple):
def between(self, other):
# returns True if other is between the values of tuple
# regardless of order
return min(self) < other < max(self)
# or if you want False for MyTuple([2,1]).between(1.5)
# return self[0] < other < self[1]
mt=MyTuple([1,2])
print mt.between(1.5)
# True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.