[英]Python- compare dictionary values (list) and get key
I have a dictionary EllipseDict
of length len(EllipseDict)=309
, I need to compare the values and return tuple of keys which have an intersection. 我有一个长度为
len(EllipseDict)=309
的字典EllipseDict
,我需要比较值并返回具有交集的键的元组。 This is the code I have written, it takes about 52.43 seconds
. 这是我编写的代码,大约需要
52.43 seconds
。 Can anyone suggest any improvements to this code ? 任何人都可以提出对此代码的任何改进建议吗?
checked = []
intersectingEllipses = []
for k1, v1 in EllipseDict.items():
for k2, v2 in EllipseDict.items():
if k1 == k2:
continue
else:
if (k1, k2) and (k2, k1) not in checked:
checked.append((k1, k2))
common = set(v1).intersection(v2)
if len(common) != 0:
intersectingEllipses.append((k1, k2))
A compound if statement with an and
is interpreted like so: 带有
and
复合if语句的解释如下:
if [condition A] and [condition B]
Now take a look at your if statement: 现在看一下您的if语句:
if (k1, k2) and (k2, k1) not in checked
This is true when: 在以下情况下会如此:
(k1, k2)
is truthey (this is your [condition A]
) AND (k1, k2)
是真理(这是您的[condition A]
)并且 (k2, k1)
is not in checked
(this is your [condition B]
) (k2, k1)
未checked
(这是您的[condition B]
) What you probably meant was to check that the two tuples ( (k1, k2)
and (k2, k1)
) are not in checked
. 您可能的意思是检查两个元组(
(k1, k2)
和(k2, k1)
)是否未checked
。 For that, you need to change your condition to: 为此,您需要将条件更改为:
if (k1, k2) not in checked and (k2, k1) not in checked
Now your conditions are 现在你的条件是
(k1, k2)
is not in checked
AND (k1, k2)
未checked
并且 (k2, k1)
is not in checked
(k2, k1)
未checked
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.