Python比较字典值(list)和get键

2024-04-25 21:59:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典EllipseDict的长度len(EllipseDict)=309,我需要比较有交集的键的值和返回元组。这是我写的代码,大约需要52.43 seconds。有人能对这段代码提出改进建议吗?你知道吗

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))

Tags: 代码inforlenifitemsk2k1
1条回答
网友
1楼 · 发布于 2024-04-25 21:59:38

带有and的复合if语句的解释如下:

if [condition A] and [condition B]

现在看看你的if语句:

if (k1, k2) and (k2, k1) not in checked

这是正确的,当:

  • (k1, k2)是真实的(这是你的[condition A])和
  • (k2, k1)不在checked(这是你的[condition B]

您可能的意思是检查两个元组((k1, k2)(k2, k1))是否不在checked中。为此,您需要将您的条件更改为:

if (k1, k2) not in checked and (k2, k1) not in checked

现在你的条件是

  • (k1, k2)不在checked并且
  • (k2, k1)不在checked

相关问题 更多 >