【问题标题】:python: shape mismatch when adding an item to a listpython:将项目添加到列表时形状不匹配
【发布时间】:2019-01-05 08:16:12
【问题描述】:

我使用 matplotlib 从带有字符串和整数的字典中绘制图表,当我绘制带有初始值的图表时它可以工作,但是如果我向字典添加另一个键 比如说

ADD,example,example.com,20.0

当我再次绘制图表时,它会给出以下错误

"ValueError: shape mismatch: objects cannot be broadcast to a single shape"

但是这个问题只发生在这个图表上,每当我使用饼图时,我都可以将项目添加到字典中,并再次成功地绘制饼图。

比我更有经验的人可以告诉我我做错了什么吗?

这是我的代码中针对此问题的相关部分 感谢您的宝贵时间。

import numpy as np
import matplotlib.pyplot as plt
empresas = { "Prodsmart": ["prodsmart.com",1.5],"James": ["james.finance",3.9],
            "Talkdesk": ["talkdesk.com",24.5], "Codacy": ["codacy.com",6.7],
            "Veniam": ["veniam.com", 26.9], "Sensei": ["sensei.tech",0.5]}


def add_empresa(info):
    empresas[info[0]] = [info[1],float(info[2])]

nlist = []
for x, k in empresas.items():
    nlist.append(k[1]) 

def graph1():
    group_data = nlist
    group_names = list(empresas.keys())
    fig, ax = plt.subplots()
    ax.barh(group_names, group_data)
    plt.show()
    return        

inputs = ""
while inputs != "EXIT":
    inputs = input("insert a command:" )
    inputzs = inputs.split(",")
    if inputzs[0] == "ADD" and len(inputzs) == 4:
        add_empresa(inputzs[1:])        
    elif inputzs[0] == "PLOT":
        graph1()

【问题讨论】:

  • 你还需要在graph1中创建nlist,否则在字典中添加新条目后group_data会比group_names短。此外,同时提取键和值,您不能依赖字典对于 3.7 之前的 Python 版本保持有序。

标签: python python-3.x numpy matplotlib


【解决方案1】:

nlist(因此group_data)在 while 循环之前创建一次。因此,一旦您在 while 循环中向字典中添加新项目,empresas 将比nlist 拥有更多元素,因此在您对graph1 的调用中group_names 将比group-data 长。

要解决此问题,请在对 graph1 的调用中提取 group_data 的值:

def graph1():
    gen = ((k, v[1]) for k, v in empresas.items())
    group_names, group_data = zip(*gen)
    fig, ax = plt.subplots()
    ax.barh(group_names, group_data)
    plt.show()

【讨论】:

  • graph1 中创建了nlist,就像您在之前的评论中建议的那样,它奏效了,谢谢。另外,是否有必要像您建议的那样从group_data 中提取值?因为刚刚创建nlist = [] for x, k in empresas.items(): nlist.append(k[1]) 解决了它
  • 只要不向字典中添加元素,对键或值的迭代应该会产生相同的顺序。不过,我不知道这是否得到保证。
猜你喜欢
  • 1970-01-01
  • 2019-06-10
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多