【发布时间】:2013-09-21 07:32:19
【问题描述】:
我正在尝试将一行 Perl 代码转换为 Python,但遇到了 Python 的 sorted() 方法的障碍。 Python 没有像 Perl 那样的本地哈希支持,所以我使用 autodict() 来复制 Perl 的哈希行为。下面是关于如何进行排序的代码 sn-p。
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 版本是基于“索引”进行排序
【问题讨论】:
-
如果您还没有看到它,这可能会对您有所帮助:wiki.python.org/moin/HowTo/Sorting
-
“Python 没有像 Perl 那样的原生哈希支持”——你在说什么? dicts 是 Python 中的基本数据类型。你在寻找自动复活吗?您可以通过
def tree(): return collections.defaultdict(tree)获得。
标签: python perl sorting hash translate