简体   繁体   English

确保两次不在字典中的相同值上执行操作的最佳方法?

[英]Best way to ensure that an operation is not performed on the same value in a dictionary twice?

Currently I am doing it like this.. 目前,我正在这样做。

def operation(x):
    return x

items_seen = []
d = {"a":10, "b": 5,"c": 6,"d": 7, "e": 7}

for x in d.values():

    if x not in items_seen:
        print operation(x)
        items_seen.append(x)

But I was wondering if there was a better way.. ? 但是我想知道是否有更好的方法。

You can convert your values list to a set first to ensure that every value only occurs once: 您可以先将值list转换为set以确保每个值仅出现一次:

for x in set(aList.values()):
    print operation(x)

If you only want to apply the operation function to the unique values of a dictionary, you can iterate over the set of its values: 如果只想将operation功能应用于字典的唯一值,则可以遍历其值的set

def operation(x):
    return x

d = {"a": 10, "b": 5, "c": 6, "d": 7, "e": 7}

for x in set(d.values()):
    print operation(x)

Output 输出量

10
5
6
7

Aside: I've changed your dictionary name from aList to d for clarity. 另外:为了清楚起见,我将您的字典名称从aList更改为d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法确保对@property以外的变量执行验证? - Is there a way to ensure validation is performed on a variable than @property? 为同一个字典值创建可交换元组键的最佳方法是什么? - What's the best way to create exchangeable tuple keys for the same dictionary value? Python从字典中获取值的最佳方法? - Python best way to assume a value from dictionary? 在Python中使用字典检查键值的最佳方法 - Best way to check key value with dictionary in python 检查列表字典中是否有值的最佳方法? - Best way to check if value in dictionary of lists? 使用不同参数两次运行相同规则的最佳方法 - Best way to run same rule twice with different params Python词典的价值是另一本词典-最好的方法? - Python dictionary's value is another dictionary — the best way? 在python中确保字典作为另一个类的构造函数中的参数传递的最佳方法/实践是不是已经变异了? - What is the best way/practice to ensure in python that the dictionary passed as an argument in the constructor of another class, is not mutated? 将字符串变量作为字符串值存储在字典中的最佳方法是什么? - What is the best way to store a string variable as a string value in a dictionary? 在词典列表中搜索Python字典值的最佳方法是什么? - What's the best way to search for a Python dictionary value in a list of dictionaries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM