【问题标题】:TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'TypeError:不支持的操作数类型/:'dict_values'和'int'
【发布时间】:2017-04-27 16:24:57
【问题描述】:

当我进行数据分析练习时,此代码在 Python3 中没有按预期运行。

类型错误是“TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'”。

我该如何解决?

import numpy as np
# Summarize the data about minutes spent in the classroom
total_minutes = total_minutes_by_account.values()
total_minutes = np.array(total_minutes)
print('Mean:', np.mean(total_minutes))
print('Standard deviation:', np.std(total_minutes))
print('Minimum:', np.min(total_minutes))
print('Maximum:', np.max(total_minutes))

【问题讨论】:

  • 在python3中,dict.values返回一个dict_values对象,它不是listtuple。尝试将其强制到列表中。 total_minutes = list(total_minutes_by_account.values()).

标签: python-3.x numpy


【解决方案1】:

在学习本课程时,这段代码也给我带来了一些意想不到的麻烦,但我通过进行以下更改使其工作:

import numpy as np

total_minutes = list(total_minutes_by_account.values())
print ('Mean:', np.mean(total_minutes))
print ('Standard Deviation:', np.std(total_minutes))
print ('Minimum:', np.min(total_minutes))
print ('Maximum:', np.max(total_minutes))

【讨论】:

    【解决方案2】:

    希望这会有所帮助:

    该类是用 Python 2 编写的,其中 Dict.values() 返回一个列表,但在 Python 3 中已更新为返回一个字典视图,如下所述: https://docs.python.org/3/library/stdtypes.html#dict-views

    这是一个潜在有用的更改,因为视图将在字典内容更新时更新,但它们的行为不像 List 和 numpy 的 meanstdmin 和 @987654327 @all 将列表作为参数。

    【讨论】:

      【解决方案3】:
      total_minutes = total_minutes_by_account.values()
      

      变量total_minutes 的类型为dict_values。 要将其转换为列表,您需要将其包装在 list 函数中,如下所示:

      total_minutes = list(total_minutes_by_account.values())
      

      【讨论】:

        【解决方案4】:

        @hpaulj 在 (not being able to do numpy operations on values on a dictionary) 给出了一个很好的例子

        在下面找到他的答案摘要。这对我帮助很大。

        In [1618]: dd = {'a':[1,2,3], 'b':[4,5,6]}
        In [1619]: dd
        Out[1619]: {'a': [1, 2, 3], 'b': [4, 5, 6]}
        In [1620]: dd.values()
        Out[1620]: dict_values([[1, 2, 3], [4, 5, 6]])
        In [1621]: np.mean(dd.values())
        ... 
        TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'
        

        解决方案: 将 dict_values 转换为列表:

        In [1623]: list(dd.values())
        Out[1623]: [[1, 2, 3], [4, 5, 6]]
        In [1624]: np.mean(list(dd.values()))
        Out[1624]: 3.5
        

        在 Py3 中,range 和 dict.keys() 需要相同的额外操作。

        ========

        np.mean 首先尝试将输入转换为数组,但使用 values() 这不是我们想要的。它创建了一个包含整个对象的单个项目对象数组。

        In [1626]: np.array(dd.values())
        Out[1626]: array(dict_values([[1, 2, 3], [4, 5, 6]]), dtype=object)
        In [1627]: _.shape
        Out[1627]: ()
        In [1628]: np.array(list(dd.values()))
        Out[1628]: 
        array([[1, 2, 3],
               [4, 5, 6]])
        

        【讨论】:

          猜你喜欢
          • 2017-12-27
          • 2014-03-31
          • 2012-12-12
          • 2020-02-27
          • 2021-05-23
          • 2016-04-15
          • 2019-01-12
          • 2012-11-29
          • 2012-12-31
          相关资源
          最近更新 更多