[英]Python 3.x's dictionary view objects and matplotlib
在python 3.x keys()
, values()
和items()
返回views 。 現在,盡管視圖當然具有優勢 ,但它們似乎也引起了一些兼容性問題。 例如,使用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())
這會引發TypeError: float() argument must be a string or a number, not 'dict_values'
python 3.4中的TypeError: float() argument must be a string or a number, not 'dict_values'
。
雖然對於最小的示例,異常非常清楚, 但是由於相同的問題而引起了這個問題,並且這里的異常少了很多: 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
)中解決此問題,或者我們應該在使用matplotlib
時開始寫list(dict.values())
類的東西,以確保不會遇到麻煩與python 3.x?
該錯誤的更多信息:
--> 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'
因此,最小的示例是:
np.array(d.keys(),dtype=float)
沒有dtype規范
In [16]: np.array(d.keys())
Out[16]: array(dict_keys([1, 3]), dtype=object)
dict_keys
被視為一個object
。 通常,您必須努力避免將np.array
將對象視為數字列表。
In [17]: np.fromiter(d.keys(),dtype=float)
Out[17]: array([ 1., 3.])
np.fromiter
可以處理d.keys()
,將其視為可迭代的。 因此, fromiter
如何處理與np.array
不同的iterable有一些細節。
生成器表達式的工作方式相同,例如(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()的現有用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.