数组的排序与awk中的多维数组有何不同? [英] How does sorting for arrays of arrays differ to multidimensional arrays in awk?

查看:36
本文介绍了数组的排序与awk中的多维数组有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,列出了一组具有组件的项目,这些组件又具有awk的属性.

I have approached the a problem to list a set of items, which have components, which in turn have properties in awk.

我试图用两种方式解决这个问题.

I have tried to approach the problem in two ways.

1)定义一个数组 list [item-number,component-number] [properties].
2)定义一个数组 list [item-number] [component-number] [properties].

1) Define an array list[item-number,component-number][properties].
2) Define an array list[item-number][component-number][properties].

这在很多方面都很有趣,因为我注意到(2)保持插入顺序,而(1)则没有.我知道数组在awk中是关联的,这很可能是巧合.但是,由于插入顺序在我的情况下很重要(而且,我想了解有关awk的更多信息),所以我想知道这是怎么回事以及为什么.

This was in many ways interesting, as I noticed (2) maintain the order of insertion, while (1) does not. I know arrays are associative in awk and it could very well be a coincidence this happened. However, as the order of insertion is important in my case (and also, I want to learn more about awk), I would like to know if this is what happening and why.

有什么想法吗?BR帕特里克

Any ideas? BR Patrik

推荐答案

这两种方法都不会保留有关插入顺序的任何信息,如果看起来任何一种都没有,那么这只是巧合.如果插入顺序对您很重要,则需要编写一些代码来跟踪该顺序,例如

Neither approach retains any information on the order of insertion, if it seems like either does then that is just coincidence. If the order of insertion is important to you then you need to write some code to track that order, e.g.

key = foo FS bar
if ( !(key in list) ) {
    keys[++numKeys] = key
}
list[key] = whatever

将按插入顺序为您提供索引的数组 keys [] 和一个将每个键映射到其值的数组 list [] 以后做:

would give you an array keys[] of the indices in the order they are inserted and an array list[] that maps each key to it's value so you can later do:

for (keyNr=1; keyNr<=numKeys; keyNr++) {
    key = keys[keyNr]
    print list[key]
}

或类似功能,以按插入顺序打印 list [] 的内容.

or similar to print the contents of list[] in the order they were inserted.

这篇关于数组的排序与awk中的多维数组有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆