如何使“看得见"用python dict哈希? [英] How to make "seen" hash with python dict?

查看:42
本文介绍了如何使“看得见"用python dict哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

推荐答案

使用

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哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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