Perl中有一种构造(称为“哈希片段”),可以使用列表对哈希进行索引,以获取列表,例如:
%bleah = (1 => 'a', 2 => 'b', 3 => 'c');
print join(' ', @bleah{1, 3}), "\n";
执行后返回:
a c
在Python中,我知道最简单、最易读的方法是使用列表推导式:
>>> bleah = {1: 'a', 2: 'b', 3: 'c'}
>>> print ' '.join([bleah[n] for n in [1, 3]])
a c
因为:
>>> bleah[[1, 2]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
我是否遗漏了其他更好的方法?也许是在Python3中,我还没有使用过它?如果没有,是否有人知道是否已经提交了PEP?我的谷歌搜索无法找到任何信息。
"这不是Pythonic":是的,我知道,但我希望它是。它很简洁易读,并且由于使用不可哈希类型索引字典永远不会成为Pythonic,因此,异常处理程序为您迭代索引而不是抛出异常,不会破坏大多数当前代码。
注意:正如评论中指出的那样,这个测试用例可以重写为一个列表,完全避免使用字典,但我正在寻找一般解决方案。
bleah.items([1,3])
返回[('1','a'),('3','c')]
或者使用bleah.values([1,3])
返回['a','c']
。 - koffeinitemgetter
。 - thefourtheye@hash{"a", "c"} = split "|", "foo|bar"
。 - tobyink