python報(bào)錯(cuò)TypeError: ‘NoneType‘ object is not subscriptable的解決方法
發(fā)現(xiàn)問題
寫python的時(shí)候出現(xiàn)了這個(gè)錯(cuò),然后網(wǎng)上的教程的解決方案幾乎都是——“重新定義下這個(gè)變量”,看的我一臉懵逼
后來發(fā)現(xiàn)原來是我把return None的方法賦給了變量,之后操作變量導(dǎo)致的,直接上代碼
for i in range(2000): read_lines = random.shuffle(read_lines) # 問題出在這里了 print(read_lines)
咋一看是沒啥問題,但是一運(yùn)行就報(bào)錯(cuò)
>>TypeError: ’NoneType’ object is not subscriptable
后來發(fā)現(xiàn)原來 random.shuffle這個(gè)函數(shù)他是return None的,但是我把他賦值給了read_lines,導(dǎo)致后續(xù)在操作read_lines的時(shí)候一直都是這個(gè)報(bào)錯(cuò),包括打印read_lines也報(bào)錯(cuò)
這個(gè)是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報(bào)錯(cuò)TypeError: ‘NoneType‘ object is not subscriptable解決方法的文章就介紹到這了,更多相關(guān)python報(bào)錯(cuò)TypeError解決內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP的Global.asa文件技巧用法2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. ASP中if語句、select 、while循環(huán)的使用方法4. ASP中常用的22個(gè)FSO文件操作函數(shù)整理5. SharePoint Server 2019新特性介紹6. 告別AJAX實(shí)現(xiàn)無刷新提交表單7. Vue+elementUI下拉框自定義顏色選擇器方式8. PHP函數(shù)原理理解詳談9. XML入門的常見問題(四)10. 使用css實(shí)現(xiàn)全兼容tooltip提示框
