本文介绍了Python:字典列表,如果存在增加一个字典值,如果不附加一个新的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情.

list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/',
                'http://www.google.cn/', 'http://www.google.com/',
                'http://www.google.fr/', 'http://www.google.fr/',
                'http://www.google.fr/', 'http://www.google.com/',
                'http://www.google.fr/', 'http://www.google.com/',
                'http://www.google.cn/']

urls = [{'url': 'http://www.google.fr/', 'nbr': 1}]

for url in list_of_urls:
    if url in [f['url'] for f in urls]:
         urls[??]['nbr'] += 1
    else:
         urls.append({'url': url, 'nbr': 1})

我该怎么办?不知道是应该拿元组来编辑还是算出元组索引?

How can I do ? I don't know if I should take the tuple to edit it or figure out the tuple indices?

有什么帮助吗?

推荐答案

这是一种非常奇怪的组织方式.如果您存储在字典中,这很容易:

That is a very strange way to organize things. If you stored in a dictionary, this is easy:

# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
    if not url in urls_d:
        urls_d[url] = 1
    else:
        urls_d[url] += 1

这段用于更新计数字典的代码是 Python 中常见的模式".有一个特殊的数据结构 defaultdict 很常见,它的创建只是为了让这更容易:

This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict, created just to make this even easier:

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

如果您使用密钥访问 defaultdict,并且该密钥不在 defaultdict 中,则该密钥会自动添加一个默认值.defaultdict 接受您传入的可调用对象,并调用它以获取默认值.在本例中,我们传入了 class int;当 Python 调用 int() 时,它返回一个零值.所以,当你第一次引用一个 URL 时,它的计数被初始化为零,然后你给计数加一.

If you access the defaultdict using a key, and the key is not already in the defaultdict, the key is automatically added with a default value. The defaultdict takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int; when Python calls int() it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.

但是一个充满计数的字典也是一种常见的模式,所以 Python 提供了一个现成的类: containers.Counter 你只需通过以下方式创建一个 Counter 实例调用类,传入任何可迭代对象;它构建了一个字典,其中键是可迭代对象的值,而值是键在可迭代对象中出现的次数的计数.上面的例子就变成了:

But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter You just create a Counter instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:

from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

如果你真的需要按照你展示的方式来做,最简单和最快的方法是使用这三个示例中的任何一个,然后构建你需要的那个.

If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

如果您使用的是 Python 2.7 或更高版本,则可以单行:

If you are using Python 2.7 or newer you can do it in a one-liner:

from collections import Counter

urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]

这篇关于Python:字典列表,如果存在增加一个字典值,如果不附加一个新的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:59