1

我正在尝试将一行 Perl 代码转换为 Python,但遇到了 Python 的 sorted() 方法的障碍。Python 没有像 Perl 那样的本地哈希支持,所以我使用 autodict() 来复制 Perl 的哈希行为。下面是有关如何完成排序的代码片段。

珀尔:

hash{one}{"index"} = 1
hash{one}{"value"} = "uno"
hash{two}{"index"} = 2
hash{two}{"value"} = "dos"
hash{three}{"index"} = 3
hash{three}{"value"} = "tres"
foreach my $ctg (sort hash{$a}{"index"} <=> hash{$b}{"index"}} keys %{ hash })

Python:

hash[one]["index"] = 1
hash[one]["value"] = "uno"
hash[two]["index"] = 2
hash[two]["value"] = "dos"
hash[three]["index"] = 3
hash[three]["value"] = "tres"
for ctg in sorted(hash):

上面的翻译并不完全正确。Python 版本基于散列中的第一个元素进行排序,即一、二、三。但是 Perl 版本是根据“索引”进行排序的

4

1 回答 1

2

首先,您的 Python 代码不会运行:hash没有定义,并且键必须是字符串,除非您在其他地方定义了它们。

这可能更接近您想要的,但是,我无法理解最后一行中的 Perl。

hash = {}
hash['one']  = {"index": 1, "value": "uno"}
hash['two']  = {"index": 2, "value": "dos"}
hash['three']= {"index": 3, "value": "tres"}
for ctg in sorted(hash.keys(),key=lambda x: hash[x]['index']):
   print hash[ctg]['index'],hash[ctg]['value']

此代码返回:

1 uno
2 dos
3 tres

sorted()函数中,我们可以定义 akey来指示我们希望它如何排序。在您的情况下,它是按键排序的,因为这就是哈希上的迭代器返回的内容,但是我们已经明确声明了对字典键的排序,然后是基于该字典中的值的排序键。

于 2013-09-17T03:17:35.280 回答