簡體   English   中英

在元組列表中查找一個元組,如果不存在則添加

[英]Find a tuple in a list of tuples and add if not present

有一個帶有元組列表的無向圖,其中每個元素都是 (id1,id2) 形式的元組。 我必須找到一個新的 (s,t) 是否存在於包含所有邊的元組列表中,如果不存在則添加元組。 邊是元組列表

def add_edge(s: str, t: str) -> None:
       
        if (s,t) or (t,s) not in edges:
            edges.append((s,t))
        return edges

但這在計算 (a,b) = (b,a) 形式的重復項時失敗了

這會很好用

def add_edge(s: str, t: str) -> None:
       
        if (s,t) not in edge and (t,s) not in edges:
            edges.append((s,t))
        return edges
if (s,t) or (t,s) not in edges

這不是你想的那樣。 (s,t)被單獨視為一個單獨的條件。 所以聲明真的是這樣的:

(s,t)
or
(t,s) not in edges

並且由於(s,t)是一個非空序列,因此整個語句自動為真。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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