简体   繁体   English

如何仅在 GNU Smalltalk 上获取密钥?

[英]How to just get key only on GNU Smalltalk?

I am currently using sortedCollection that stores dictionary of character (key) and number of occurrence for that character (value).我目前正在使用 sortedCollection 存储字符(键)字典和​​该字符(值)的出现次数。 When iterating through sortedCollection, how do I access the key value only?迭代 sortedCollection 时,如何仅访问键值?

eg例如

[que last notNil] whileTrue: [
    stdout << 'current character is ' *key* << ' and occurs << *val* << ' times.' << nl.
]

Where que is the sortedCollection that sorts dictionary by value.其中que是按值对字典进行排序的 sortedCollection。

My goal is following: let's say que has: [$a:20, $e:100] where first letter is the key of dictionary and second number is the value of dictionary.我的目标如下:假设que有: [$a:20, $e:100]其中第一个字母是字典的键,第二个数字是字典的值。 My output should look something like this:我的输出应该是这样的:

current character is a and occurs 20 times. current character is e and occurs 100 times.

I am not sure how to get a , or the key in dictionary since keys are arbitrary.我不确定如何获得a或字典中的键,因为键是任意的。

Assuming that que is a sorted collection and each element is an Association with the character as the key and the count as the value, as in your [$a:20, $e:100] example, you could do it like this:假设que是一个排序集合,每个元素都是一个 Association,以字符为键,以计数为值,如在您的[$a:20, $e:100]示例中,您可以这样做:

que do: [:each | stdout << 'current character is ' << each key
                        << ' and occurs ' << each value << ' times.' << nl]

If que is a Dictionary, use que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl]如果 que 是字典,请使用que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl] que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl] . que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl]

Depending on your overall application, you could also use a Bag , which is an unordered collection of elements that can appear multiple times (as opposed to a Set, which contains each element only once).根据您的整体应用程序,您还可以使用Bag ,它是一个可以多次出现的无序元素集合(而不是一个 Set,它只包含每个元素一次)。

characters := 'hello world' asBag.
characters asSet do: [:each |
    stdout << 'current character is ' << each
           << ' and occurs ' << (characters occurrencesOf: each) 
           << ' times.' << nl]

You could also have a look at the # sortedByCount method and see whether it suits your case.您还可以查看 # sortedByCount方法,看看它是否适合您的情况。 I cannot tell from the reference how exactly its returned collection is structured, so I will not provide you with guessed example code.我无法从参考资料中得知其返回的集合的结构究竟如何,因此我不会为您提供猜测的示例代码。

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

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