[英]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.