简体   繁体   English

Smalltalk - 用条件迭代字典数组

[英]Smalltalk - iterate over a dict array with conditions

I'm working on a Smalltalk small method, I want this method to iterate over a dictionary array and to return True or False depend on the conditions.我正在研究一个 Smalltalk 小方法,我希望这个方法迭代字典数组并根据条件返回 True 或 False。

The dictionary array is an instance variable, name dictArray.字典数组是一个实例变量,名称为 dictArray。

It looks like: [{'name': toto, 'age': 12}, {'name': tata, 'age': 25}]它看起来像: [{'name': toto, 'age': 12}, {'name': tata, 'age': 25}]

So I want to iterate over dictArray and verify for each item the name and the age.所以我想遍历 dictArray 并验证每个项目的名称和年龄。 If it matches I return true else false and the end of the iteration.如果匹配,我返回 true else false 和迭代结束。

In python it should look like:在python中它应该是这样的:

for item in dictArray:
    if item['name'] == aName and item['age'] == aAge:
        return True
return False

I can't find documentation with this special case (array iteration + condition + return)我找不到这种特殊情况的文档(数组迭代 + 条件 + 返回)

Hope someone can help me!希望可以有人帮帮我!

To test whether a Collection contains an element that matches a condition, use anySatisfy: .要测试 Collection 是否包含与条件匹配的元素,请使用anySatisfy: It answers true iff there is a matching element.如果存在匹配元素,则它回答为真。

dictArray anySatisfy: [:each | (each at: 'name') = aName and: [(each at: 'age') = anAge]]

Reference: https://www.gnu.org/software/smalltalk/manual-base/html_node/Iterable_002denumeration.html参考: https : //www.gnu.org/software/smalltalk/manual-base/html_node/Iterable_002denumeration.html

The way described above is the preferred way to write it.上面描述的方式是编写它的首选方式。 The following is only for explanation how it relates to your Python code example.以下仅用于说明它与您的 Python 代码示例的关系。

anySatisfy: can be implemented in terms of do: anySatisfy:可以通过do:来实现do:

anySatisfy: aBlock
   self do: [:each | (aBlock value: each) ifTrue: [^ true]].
   ^ false

Or spelled out with your condition:或详细说明您的情况:

dictArray do:
   [:each |
   ((each at: 'name') = aName and: [(each at: 'age') = anAge])
      ifTrue: [^ true]].
^ false

This is the equivalent of your Python code.这相当于您的 Python 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM