我有一個這樣的列舉:
class AgeCategory(Enum):
Child = slice(None, 16)
YoungAdult = slice(16, 25)
...
Old = slice(85, None)
它基本上提供了每個類別中的年齡范圍(以年為單位)。
我想要一個函式來檢查某個值對應于哪個年齡范圍。這是我的想法:
def get_category(age: int) -> AgeCategory:
for age_range in AgeCategory:
if age in age_range.value #check if it's in the slice for that enum
return age_range
else:
assert False, "unreachable"
然而assert 5 in slice(1,10)失敗。OFC 我可以做這樣的事情:
s: slice = age_range.value
if s.start <= age < s.stop: #bounds check
return age_range
但這忽略了 step 引數,感覺就像是在重新發明輪子。
表達這些年齡范圍的 Pythonic 方式是什么?它們被用作這樣的切片:
ya_data = np.sum(some_data[AgeCategory.YoungAdult])
uj5u.com熱心網友回復:
在您的情況下,它不是那么重要,但這應該比處理大切片時的迭代更快:
a_slice = slice(4, 15, 3)
def is_in_slice(a_slice, idx):
if idx < a_slice.start or idx >= a_slice.stop:
return False
step = a_slice.step if a_slice.step else 1
if (idx - a_slice.start) % step == 0:
return True
else:
return False
test_array = np.where([is_in_slice(a_slice, idx) for idx in range(20)])[0]
print(test_array)
[ 4 7 10 13]
并測驗非常大的切片:
a_big_slice = slice(0, 1_000_000_000_000, 5)
print(is_in_slice(a_big_slice, 999_000_000_005))
print(is_in_slice(a_big_slice, 999_000_000_004))
True
False
uj5u.com熱心網友回復:
使用樣本切片:
In [321]: child=slice(None,16,4)
我正在考慮將其擴展為串列或陣列。但arange無法處理None:
In [323]: np.arange(child.start,child.stop,child.step)
Traceback (most recent call last):
File "<ipython-input-323-b2d245f287ff>", line 1, in <module>
np.arange(child.start,child.stop,child.step)
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
np.r_能夠。在這里,numpy 開發人員已經完成了翻譯所有切片選項的所有作業:
In [324]: np.r_[child]
Out[324]: array([ 0, 4, 8, 12])
In [325]: 3 in _
Out[325]: False
In [327]: 4 in __
Out[327]: True
它可能不是最快的,但似乎是最通用的方法 - 您無需做很多作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368005.html
上一篇:使用布爾矩陣從資料幀中提取向量
