Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确保不会对字典中的同一值执行两次操作的最佳方法是什么?_Python - Fatal编程技术网

Python 确保不会对字典中的同一值执行两次操作的最佳方法是什么?

Python 确保不会对字典中的同一值执行两次操作的最佳方法是什么?,python,Python,目前我是这样做的 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) 但我想知道是否有更好的方法 您可以先将值列表转换为集合,以确保每个值只出现一次: f

目前我是这样做的

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)

但我想知道是否有更好的方法

您可以先将值
列表
转换为
集合
,以确保每个值只出现一次:

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

如果只想将
操作
函数应用于字典的唯一值,则可以迭代其值的
集合

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)
输出

10
5
6
7

旁白:为了清楚起见,我把你的字典名从
aList
改为
d

你想用这段代码实现什么?是的,这样更好。谢谢顺便说一句,如果是这样呢。d={“a”:[10,0],“b”:[5,0],“c”:[6,0],“d”:[7,0],“e”:[7,0]}我想在x[0]上执行操作?您可以在集合中为x(映射(元组,d.values()):打印操作(x[0])。为了正确地解释,可能需要一个不同的问题……基本上列表是不可散列的,因此您必须将列表的
列表转换为元组列表