Сравнение образцов с ассоциациями
Версия 11 представляет несколько функций для упрощения манипуляции и соотношения образцов ассоциаций.
Используйте KeyMemberQ и KeyFreeQ для проверки того, является ли ключ частью ассоциации.
In[1]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_72.png)
KeyMemberQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[1]=
![](assets.ru/pattern-matching-with-associations/O_75.png)
In[2]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_73.png)
KeyFreeQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[2]=
![](assets.ru/pattern-matching-with-associations/O_76.png)
KeyValuePattern позволяет Вам соотнести законченную ассоциацию, содержащую два или больше заданных правила.
In[3]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_74.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[b -> _]]
Out[3]=
![](assets.ru/pattern-matching-with-associations/O_77.png)
In[4]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_75.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[{c -> _, a -> _}]]
Out[4]=
![](assets.ru/pattern-matching-with-associations/O_78.png)
Рассчитайте данные о гравитационном поле в нескольких точках Земли.
In[5]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_76.png)
points = {{40, -100, 691}, {30, -120, 560}, {80, 70, 91}};
data = GeogravityModelData /@ points
Out[5]=
![](assets.ru/pattern-matching-with-associations/O_79.png)
Выберите случаи, для которых магнитуда поля больше, чем общее среднее значение.
In[6]:=
![Click for copyable input](assets.ru/pattern-matching-with-associations/In_77.png)
Cases[data,
KeyValuePattern[
"Magnitude" -> _?(GreaterThan[
Quantity[1, "StandardAccelerationOfGravity"]])]]
Out[6]=
![](assets.ru/pattern-matching-with-associations/O_80.png)
Используйте KeyValueMap для дальнейшей обработки каждой пары "ключ-значение".
In[7]:=
![Click for copyable input](assets.ru/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.ru/pattern-matching-with-associations/O_81.png)