[英]Find a tuple in a list of tuples and add if not present
There is an undirected graph with a list of tuples where each element is a tuple in the form of (id1,id2).有一个带有元组列表的无向图,其中每个元素都是 (id1,id2) 形式的元组。 I have to find whether a new (s,t) is present in the list of tuples which contains all the edges and add the tuple if it is not present.
我必须找到一个新的 (s,t) 是否存在于包含所有边的元组列表中,如果不存在则添加元组。 edges is the list of tuples
边是元组列表
def add_edge(s: str, t: str) -> None:
if (s,t) or (t,s) not in edges:
edges.append((s,t))
return edges
But this fails in acoounting for duplicates of the form (a,b) = (b,a)但这在计算 (a,b) = (b,a) 形式的重复项时失败了
this will work well这会很好用
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
This is not doing what you think.这不是你想的那样。
(s,t)
is treated as a separate condition all on its own. (s,t)
被单独视为一个单独的条件。 So the statement is really this:所以声明真的是这样的:
(s,t)
or
(t,s) not in edges
And since (s,t)
is a non-empty sequence, the entire statement is automatically true.并且由于
(s,t)
是一个非空序列,因此整个语句自动为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.