![](/img/trans.png)
[英]Is there a way to ensure validation is performed on a variable than @property?
[英]Best way to ensure that an operation is not performed on the same value in a dictionary twice?
目前,我正在這樣做。
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)
但是我想知道是否有更好的方法。
您可以先將值list
轉換為set
以確保每個值僅出現一次:
for x in set(aList.values()):
print operation(x)
如果只想將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)
輸出量
10
5
6
7
另外:為了清楚起見,我將您的字典名稱從aList
更改為d
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.