python報錯TypeError: ‘NoneType‘ object is not subscriptable的解決方法
發(fā)現(xiàn)問題
寫python的時候出現(xiàn)了這個錯,然后網(wǎng)上的教程的解決方案幾乎都是——“重新定義下這個變量”,看的我一臉懵逼
后來發(fā)現(xiàn)原來是我把return None的方法賦給了變量,之后操作變量導(dǎo)致的,直接上代碼
for i in range(2000): read_lines = random.shuffle(read_lines) # 問題出在這里了 print(read_lines)
咋一看是沒啥問題,但是一運行就報錯
>>TypeError: ’NoneType’ object is not subscriptable
后來發(fā)現(xiàn)原來 random.shuffle這個函數(shù)他是return None的,但是我把他賦值給了read_lines,導(dǎo)致后續(xù)在操作read_lines的時候一直都是這個報錯,包括打印read_lines也報錯
這個是random庫里面的代碼(看他的注釋里面說的是return None)
def shuffle(self, x, random=None): ''' Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. ''' if random is None: randbelow = self._randbelow for i in reversed(range(1, len(x))):# pick an element in x[:i+1] with which to exchange x[i]j = randbelow(i+1)x[i], x[j] = x[j], x[i] else: _int = int for i in reversed(range(1, len(x))):# pick an element in x[:i+1] with which to exchange x[i]j = _int(random() * (i+1))x[i], x[j] = x[j], x[i]
解決方案
把上面一行賦值語句改掉就好了
for i in range(2000): random.shuffle(read_lines) print(read_lines) content_list = []
總結(jié)
到此這篇關(guān)于python報錯TypeError: ‘NoneType‘ object is not subscriptable解決方法的文章就介紹到這了,更多相關(guān)python報錯TypeError解決內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. css進(jìn)階學(xué)習(xí) 選擇符2. python實現(xiàn)自動化辦公郵件合并功能3. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))4. python爬蟲beautifulsoup解析html方法5. python web框架的總結(jié)6. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式7. 解決python logging遇到的坑 日志重復(fù)打印問題8. html小技巧之td,div標(biāo)簽里內(nèi)容不換行9. Python基礎(chǔ)之numpy庫的使用10. 詳解Python模塊化編程與裝飾器
