有关联的模式匹配
版本 11 中引入了多个函数来简化关联的模式匹配操作.
用 KeyMemberQ 和 KeyFreeQ 测试键是否为关联的一部分.
In[1]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_72.png)
KeyMemberQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[1]=
![](assets.zh/pattern-matching-with-associations/O_75.png)
In[2]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_73.png)
KeyFreeQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[2]=
![](assets.zh/pattern-matching-with-associations/O_76.png)
KeyValuePattern 可以完全匹配含有一个或多个给定规则的关联.
In[3]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_74.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[b -> _]]
Out[3]=
![](assets.zh/pattern-matching-with-associations/O_77.png)
In[4]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_75.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[{c -> _, a -> _}]]
Out[4]=
![](assets.zh/pattern-matching-with-associations/O_78.png)
计算在地球多个点处的重力场数据.
In[5]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_76.png)
points = {{40, -100, 691}, {30, -120, 560}, {80, 70, 91}};
data = GeogravityModelData /@ points
Out[5]=
![](assets.zh/pattern-matching-with-associations/O_79.png)
选择场强大于标准平均值的情况.
In[6]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_77.png)
Cases[data,
KeyValuePattern[
"Magnitude" -> _?(GreaterThan[
Quantity[1, "StandardAccelerationOfGravity"]])]]
Out[6]=
![](assets.zh/pattern-matching-with-associations/O_80.png)
用 KeyValueMap 处理每对键值组.
In[7]:=
![Click for copyable input](assets.zh/pattern-matching-with-associations/In_78.png)
Cases[data,
KeyValuePattern[
"Magnitude" -> _?(GreaterThan[
Quantity[1, "StandardAccelerationOfGravity"]])]];
KeyValueMap[
EntityProperty["GeogravityModel", #1] ->
UnitConvert[#2, "Imperial"] &, First[%]]
Out[7]=
![](assets.zh/pattern-matching-with-associations/O_81.png)