【问题标题】:How to extract and plot the keys of a defaultdict based on the values如何根据值提取和绘制 defaultdict 的键
【发布时间】:2021-12-17 17:39:03
【问题描述】:

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

但如果我尝试使用 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

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

【问题讨论】:

    标签: python matplotlib defaultdict


    【解决方案1】:
    • 将过滤后的ij 解压到单独的容器中,然后进行绘图。
      • 单独处理defaultdict,然后只绘制一次,应该比多次访问绘图对象更快。
    • 使用列表理解收集所需的元组:
      • [k for k, v in ddtype.items() if v > 1.5]
    • 将元组解包到单独的对象中:
    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+')
    

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 2019-10-03
      • 2022-01-11
      相关资源
      最近更新 更多