如何对精灵中的词典进行排序

时间:2016-08-20 09:13:07

标签: vala genie

更新解决了编译错误,现在代码的唯一问题是如何按字母顺序对dict进行排序以进行漂亮的打印。

我正在将一个argument parser从python重构为Genie,但是我发现自己陷入了如何在将这些项目添加到列表之前对它们进行排序的方式。

在python中它就像:

一样简单
    lines.append("Options:")
    if len(self.options):
        for name, option in sorted(self.options.items()):
            lines.append("  %s: %s" % (name, option.values))
    else:
        lines.append("  [none]")

self.options声明为self.options = {}

现在如何打印dict的内容,但排序了?

以下是我被困的代码:

def ListOptions()
    var lines = new list of string

    lines.add("Options:")
    if _options.size != 0
        for name in _options.keys
            lines.add("  %s: %s" % (name, _options.values))
    else
        lines.add("  [none]")

ListOptions是类中的一个方法,我将_options声明为_options:string的新字典,字符串

代码的该部分中不再有编译错误。我的问题是如何在将dict的元素添加到列表lines之前对其进行排序?

2 个答案:

答案 0 :(得分:2)

dict of实际上是Gee.HashMap of K, V,因此您可以查找keys属性的类型。

keys属于Gee.Set of G类型,没有排序方法。

然而,它确实来自Gee.Collection of G,我们可以使用list of string创建一个新的临时Gee.ArrayListsort,它有sort_string_collection方法。

我把它放到[indent=4] def sorted_string_collection (collection: Gee.Collection of string): Gee.Iterable of string var l = new list of string l.add_all (collection); l.sort () return l; def list_options (_options: dict of string, string): list of string var lines = new list of string lines.add("Options:") if _options.size != 0 for name in sorted_string_collection (_options.keys) lines.add(@" $name: $(_options[name])") else lines.add(" [none]") return lines init var opts = new dict of string, string opts["z"] = "23" opts["abc"] = "42" opts["pi"] = "3.141" var l = list_options (opts) for var s in l print (s) 函数中(它甚至可以是Generic,因为它不是特定于字符串,但我没有因为it's not easily possible with Genie at the moment而烦恼。)

添加测试代码后,为了使其成为MCVE,结果如下所示:

[indent=4]

def sorted_string_collection (collection: Gee.Collection of string): Gee.Iterable of string
    var l = new list of string
    l.add_all (collection);
    l.sort ()
    return l;

init
    var dic = new dict of string, string
    dic["z"] = "23"
    dic["abc"] = "42"
    dic["pi"] = "3.141"
    for k in sorted_string_collection (dic.keys)
        print (@"$k: $(dic[k])")

甚至更简约(如果我们使用stackoverflow文档进行Genie,这将是一个很好的例子):

String sql = "..." + pass1 + "'";
                           ^

答案 1 :(得分:2)

基于Thomas和Jens的评论,人们也可以使用TreeMap。以下是它的外观:

var githubAPI = 'https://api.github.com/repos/zacharysohovich/ticTacToe/readme';
var items = {};
jQuery.ajax({
  url: githubAPI,
  contentType: 'application/json; charset=utf-8',
  success: function(resultData) {
    $.each(resultData, function(key,val) {
      items[key] = val;
    });
  }
});
var githubData = $.map(items,function(k,v) {
  return ("<p>" + k + ": " + v + "</p>");
});
相关问题