将一个常量整数添加到python字典中的值 [英] Adding a constant integer to a value in a python dictionary

查看:405
本文介绍了将一个常量整数添加到python字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果满足某些条件,您将如何在字典中添加一个常数,例如1。

How would you add a constant number, say 1, to a value in a dictionary if certain conditions are fulfilled.

例如,如果我有一个字典:

For example, if I had a dictionary:

dict = {'0':3, '1':3, '2':4, '3':4, '4':4}

如果我只想将整数1添加到字典,所以它更新dict这样:

If I simply wanted to add the integer 1 to every value in the dictionary so it updates dict as this:

dict = {'0':4, '1':4, '2':5, '3':5, '4':5}

当我使用以下代码其中Cur_FID是字典0中的第一个,它给了我一个值5?它应该已经给了我4.在gridList2中的lucodes的#$ p

When I used the following code where the Cur_FID is the first one in the dictionary '0', it gave me a value of 5? It should have given me 4. ??

for lucodes in gridList2:   # a list of the values [3,3,4,4,4] -- have to separate out because it's part of a larger nested list
    if lucodes > 1:
        if lucodes < 5:
            FID_GC_dict[Cur_FID] = lucodes + 1

print FID_GC_dict[Cur_FID]   #returned 5??? weird

我想添加1到所有的值,但是停止在这里,当第一个字典更新做某事

I want to add 1 to all the values, but stopped here when the first dictionary update did something weird.

推荐答案

一个简单的方法是使用 collections.Counter 对象,您可以以各种方式使用一个普通的字典在大多数情况下,但它被优化为保持项目的计数:

One simple way to do this is to use a collections.Counter object, which you can use in every way like a normal dictionary in most ways but it is optimized for keeping a count of items:

>>> from collections import Counter
>>> d = Counter({'0':3, '1':3, '2':4, '3':4, '4':4})
>>> d
Counter({'3': 4, '2': 4, '4': 4, '1': 3, '0': 3})
>>> d.update(d.keys())
>>> d
Counter({'3': 5, '2': 5, '4': 5, '1': 4, '0': 4})

只有在满足某些条件时才执行此操作,只需使用理解或生成器才能将要增加的密钥列表传递到 d.update()

As for only doing it when certain conditions are fulfilled, just use a comprehension or generator to only pass the list of the keys you want to increment to d.update():

>>> d = Counter({'3': 4, '2': 4, '4': 4, '1': 3, '0': 3})
>>> d.update((k for k, v in d.items() if v == 4))
>>> d
Counter({'3': 5, '2': 5, '4': 5, '1': 3, '0': 3})

这篇关于将一个常量整数添加到python字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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