簡體   English   中英

確保兩次不在字典中的相同值上執行操作的最佳方法?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM