Python 3.x的字典视图对象和matplotlib

joj*_*ojo 14 python numpy matplotlib python-3.x

在蟒蛇3.X keys(),values()items()返回意见.现在虽然视图肯定有优势,但它们似乎也会导致一些兼容性问题.例如matplotlib(最终是numpy).作为一个例子对stackexchange问题的答案只是正常工作与Python 2.x的,但在Python 3.4执行他们的时候抛出一个异常.

一个最小的例子是:

import matplotlib.pyplot as plt
d = {1: 2, 2: 10}
plt.scatter(d.keys(), d.values())
Run Code Online (Sandbox Code Playgroud)

哪个TypeError: float() argument must be a string or a number, not 'dict_values'用python 3.4 引发.

虽然对于最小的例子,Exception非常清楚,但是由于同样的问题而出现了这个问题,而且这里的Exception不太清楚:TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

处理这个问题的最佳做法是什么?我们可以希望在新版本matplotlib(或最终numpy)这个问题将得到处理或者我们应该开始写东西喜欢list(dict.values())使用的时候matplotlib只是为了确保不要碰到与Python 3.x的麻烦吗?

hpa*_*ulj 5

更多的错误:

--> 512     return array(a, dtype, copy=False, order=order, subok=True)
    513 
    514 def ascontiguousarray(a, dtype=None):

TypeError: float() argument must be a string or a number, not 'dict_values'
Run Code Online (Sandbox Code Playgroud)

所以最小的例子是:

np.array(d.keys(),dtype=float)
Run Code Online (Sandbox Code Playgroud)

没有 dtype 规范

In [16]: np.array(d.keys())
Out[16]: array(dict_keys([1, 3]), dtype=object)
Run Code Online (Sandbox Code Playgroud)

dict_keys被视为一个object。通常,您必须努力避免np.array将对象视为数字列表。

In [17]: np.fromiter(d.keys(),dtype=float)
Out[17]: array([ 1.,  3.])
Run Code Online (Sandbox Code Playgroud)

np.fromiter可以处理d.keys(),将其视为可迭代的。因此,在如何fromiter处理不同于np.array.

生成器表达式的工作方式相同,例如(i for i in range(4)). fromiter可以遍历它,array将其视为对象或引发错误。

如果 SO 提到的所有错误都归结为np.array(...)处理生成器,那么可能可以通过一个numpy更改来修复该行为。开发人员当然不想调整每个可能接受列表的函数和方法。但这感觉像是一个必须经过彻底测试的根本性变化。即便如此,它也可能会产生向后兼容性问题。

一段时间以来,公认的修复方法是将您的代码通过2to3.

https://docs.python.org/2/library/2to3.html

对于字典:

修复字典迭代方法。dict.iteritems() 转换为 dict.items(),dict.iterkeys() 转换为 dict.keys(),以及 dict.itervalues() 转换为 dict.values()。类似地,dict.viewitems()、dict.viewkeys()和dict.viewvalues()分别转换为dict.items()、dict.keys()和dict.values()。它还在对列表的调用中包装了 dict.items()、dict.keys() 和 dict.values() 的现有用法。