Python_報錯:IndexError: list assignment index out of range


今天發現一個報錯,卡了好幾個點,后來發現原因后,臉上三條黑線,尷尬啊!!!

報錯:IndexError: list assignment index out of range

 原因:split()寫法轉成列表就會認作一個整體,結果會是一個整體(示例:['gg111ggggggg222']),不是預期結果

上源碼:

def func(n,target_str):
    with open("1003.txt","r+",encoding="utf-8") as fp:
        word_str = fp.read()
        print(word_str)
        if n < len(word_str):
            word_list = word_str.split()
            word_list[n] = target_str
            print(word_list)
        else:
            print("111")

調用該方法傳入參數 func(2,"111")

報錯了:

>>> func(2,"111")
gg111ggggggg222
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in func
IndexError: list assignment index out of range

>>> def func(n,target_str):
...     with open("1003.txt","r+",encoding="utf-8") as fp:
...         word_str = fp.read()
...         print(word_str)
...         if n < len(word_str):
...             word_list = word_str.split()#這里不能這么寫啊,詳見如下說明
...             word_list[n] = target_str
...             print(word_list)
...         else:
...             print("111")
...
>>>
>>> func(2,"111")
gg111ggggggg222
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in func
IndexError: list assignment index out of range
>>>

因為我源文件"1003.txt"的內容是:gg111ggggggg222

如果按上面的split()寫法轉成列表就會認作一個整體,結果會是['gg111ggggggg222'],不是我要的結果

 

   這里的 word_str的值是:gg111ggggggg222

word_list = word_str.split()#這里不能這么寫

改成如下就好了:
word_list = list(word_str)#會將所有元素單獨賦值給列表

精簡下,就是如下意思:
str1 = "qwer"
list1 = str1.split()
list2 = list(str1)

print(list1)
print(list2)

>>> str1 = "qwer"
>>> list1 = str1.split()#該場景下會作為整體轉換為列表
>>> list2 = list(str1)#該場景下會將單個元素賦值給列表
>>>
>>>
>>> print(list1)
['qwer']
>>> print(list2)
['q', 'w', 'e', 'r']
>>> 

可參照Python_列表和字符串間的轉換  簡單說明


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM