如何根据值提取和绘制 defaultdict 的键

How to extract and plot the keys of a defaultdict based on the values

我正在使用 defalutdict(代码中的 ddtype)对象,它基本上用作三维函数,通过将每对自然元素映射到实数。

但是如果我尝试使用 matplotlib 打印具有某些特征的所有元素:

import matplotlib.pyplot as plt
from collections import defaultdict

ddtype = defaultdict(int, {(1,1):2.2,(1,2):0.7,(2,1):0.9,(2,2):1.3})

for i in range(1,3):
    for j in range(1,3):
        if (ddtype[i,j] > 1.5):
            plt.plot((i,j),'k+')

plt.show()
# The plot is saved but not here

然后程序变得非常慢(对于大范围循环),即使我经常清除内存。有没有更有效的方法来编写上面的循环? 提前谢谢你

  • 将过滤后的ij解压到单独的容器中,然后绘图。
    • 单独处理 defaultdict,然后只绘制一次,应该比多次访问绘图对象更快。
  • 使用列表理解收集所需的元组:
    • [k for k, v in ddtype.items() if v > 1.5]
  • 将元组解包到单独的对象中:
    • i, j = zip(*[...])
    • 引用Unpacking a list / tuple of pairs into two lists / tuples
from collections import defaultdict as dd
import matplotlib.pyplot as plt

ddt = dd(int, {(1, 1): 2.2, (1, 2): 0.7, (2, 1): 0.9, (2, 2): 1.3})

i, j = zip(*[k for k, v in ddt.items() if v > 1.5])

plt.plot(i, j, 'k+')