问题描述
在Perl中可以做到这一点:
In Perl one can do this:
my %seen;
foreach my $dir ( split /:/, $input ) {
$seen{$dir}++;
}
这是一种通过跟踪已看到"的内容来删除重复项的方法.在python中,您无法执行以下操作:
This is a way to remove duplicates by keeping track of what has been "seen". In python you cannot do:
seen = {}
for x in ['one', 'two', 'three', 'one']:
seen[x] += 1
上面的python导致 KeyError:'one'
.
The above python results in KeyError: 'one'
.
进行可见"哈希的python-y方法是什么?
What is python-y way of making a 'seen' hash?
推荐答案
使用 defaultdict
可获得此行为.要注意的是,您需要为defaultdict指定数据类型,以便即使没有值的键也可以使用:
Use a defaultdict
for getting this behavior. The catch is that you need to specify the datatype for defaultdict to work for even those keys which don't have a value:
In [29]: from collections import defaultdict
In [30]: seen = defaultdict(int)
In [31]: for x in ['one', 'two', 'three', 'one']:
...: seen[x] += 1
In [32]: seen
Out[32]: defaultdict(int, {'one': 2, 'three': 1, 'two': 1})
您也可以使用计数器:
>>> from collections import Counter
>>> seen = Counter()
>>> for x in ['one', 'two', 'three', 'one']: seen[x] += 1
...
>>> seen
Counter({'one': 2, 'three': 1, 'two': 1})
如果您需要的是唯一的,只需执行设置操作: set([''','two','three','one'])
If all you need are uniques, just do a set operation: set(['one', 'two', 'three', 'one'])
这篇关于如何使“看得见"用python dict哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!