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])。为了正确地解释,可能需要一个不同的问题……基本上列表是不可散列的,因此您必须将列表的值列表转换为元组列表