plot绘制各种曲线的程序,在python27下运行正常,到python35下 提示出现这个错误:
TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'
-
In python3,
dict.valuesreturns adict_valuesobject, which is not alistortuple. Try coercing that into a list.total_minutes = list(total_minutes_by_account.values()). – Abdou Apr 27 '17 at 16:40 -
It's a good idea to check the results of a
np.array(...)statement. During testing look attotal_minutes, or at least check itsshapeanddtype. Don't just assume, check. In this case thedtypeis probablyobject, not floats or ints. – hpaulj Apr 27 '17 at 17:29 -
Find below a summary of his answer. It helped me a lot.
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'Solution: convert the dict_values to list:
In [1623]: list(dd.values()) Out[1623]: [[1, 2, 3], [4, 5, 6]] In [1624]: np.mean(list(dd.values())) Out[1624]: 3.5In Py3, range and dict.keys() require the same extra touch.
========
np.mean first tries to convert the input to an array, but with values() that isn't what we want. It makes a single item object array containing this whole object.
-
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]])25行修改后 28行也要加list函数 ,否则提示如下错误(下面代码黑色两行,原来python2中无list函数)
-
numpy.core._internal.AxisError: axis -1 is out of bounds for array of dimension 0
-
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pltimport collections
import time
import pickle as pickle_since_beginning = collections.defaultdict(lambda: {})
_since_last_flush = collections.defaultdict(lambda: {})_iter = [0]
def tick():
_iter[0] += 1def plot(name, value):
_since_last_flush[name][_iter[0]] = valuedef flush():
prints = []for name, vals in _since_last_flush.items():
prints.append("{}\t{}".format(name, np.mean(list(vals.values()))))
_since_beginning[name].update(vals)
x_vals = np.sort(list(_since_beginning[name].keys()))
y_vals = [_since_beginning[name][x] for x in x_vals]plt.clf()
plt.plot(x_vals, y_vals)
plt.xlabel('iteration')
plt.ylabel(name)
plt.savefig(name.replace(' ', '_')+'.jpg')print ("iter {}\t{}".format(_iter[0], "\t".join(prints)))
_since_last_flush.clear()with open('log.pkl', 'wb') as f:
pickle.dump(dict(_since_beginning), f, pickle.HIGHEST_PROTOCOL)

本文介绍了一种在从Python 2.x迁移至Python 3.x过程中常见的错误:尝试对字典的values方法返回的对象进行数学运算导致的TypeError。通过将dict_values对象转换为列表,可以解决此问题。此外,文章还提供了如何使用np.mean等函数处理转换后的列表的具体示例。
572

被折叠的 条评论
为什么被折叠?



