提示错误“'=' not supported between instances of 'range' and 'int'”
生活随笔
收集整理的這篇文章主要介紹了
提示错误“'=' not supported between instances of 'range' and 'int'”
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在學習《Designing Machine Learning Systems with Python》(中文名《機器學習系統設計——python語言實現》)一書中,第三章第二節第三小節部分的泊松分布的python代碼在python3.6上運行時報錯
TypeError: '>=' not supported between instances of 'range' and 'int'錯誤信息很明顯,’>=’符號不支持兩個類型不同的字符之間的比較,從代碼中我們可以很容易知道
from scipy.stats import poisson import matplotlib.pyplot as plt def pois(x = 1000):xr = range(x)ps = poisson(xr)plt.plot(ps.pmf(x/2))plt.show()pois()關鍵在于poisson()函數的輸入,即xr這個變量,它的類型是range類型,而range類型不能與一個int類型直接判斷。我們只需要對它的類型進行下修改就可以了。
我們知道我們的目的是讓xr這個變量中的每一個值都與’>=’符號后的int類型數值進行下判斷,并將所有結果一起返回。那么我們就可以先試下list類型
輸入:
輸出:
Traceback (most recent call last):File "<input>", line 1, in <module> TypeError: '>=' not supported between instances of 'list' and 'int'看來不行,那么我們就想到了numpy庫中也有一個類似的arange()函數,我們測試下。
輸入:
輸出:
array([ True, True, True, True, True, True, True, True, True,True])我們得到了一個array類型的數組。這就是我們想要的答案。返回書中的例子,我們的代碼就應該修改為
import numpy as np from scipy.stats import poisson import matplotlib.pyplot as plt def pois(x = 1000):xr = np.arange(x)ps = poisson(xr)plt.plot(ps.pmf(x/2))plt.show()pois()我們就得到了我們想要的輸出。
總結
以上是生活随笔為你收集整理的提示错误“'=' not supported between instances of 'range' and 'int'”的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python计算两个二维list依据第
- 下一篇: 对标记点进行三角化