![](/img/trans.png)
[英]Python read txt file as input: IndexError: list index out of range?
[英]How to swap numbers read from a list .txt file? Error “list index out of range”
我想做的是從包含數字的.txt文件中讀取內容,然后從該列表中將數字2交換到列表中的不同位置(索引)。 從我可以看出的問題是,該列表是追加的,我的索引不再正確。 如何解決此問題,以免出現“列表索引超出范圍”錯誤。
分配任務:您在此分配中的工作是創建一個簡單的數值數據集。 從外部文件中收集數據,然后執行我們研究過的排序策略,進行交換。
open_list = open("my_list.txt")
num_list1 = []
for line in open("my_list.txt"):
line = line.strip()
num_list1.append(line)
print(num_list1) # this is printing my list perfect
# ['15,57,14,33,72,79,26,56,42,40'] is what
# prints, which is what im looking for
temp = num_list1[0] # this is where im running into issues
num_list1[0] = num_list1[2]
num_list1[2] = temp
print(num_list1)
您需要根據空間進行拆分。 使用split()代替strip()。 strip()方法返回字符串的副本,該字符串的開頭和結尾字符均被刪除(基於傳遞的字符串參數)。 而split():將字符串分割成一個列表,其中每個單詞都是一個列表項。
open_list = open(“ my_list.txt”)
num_list1 = []
for line in open("my_list.txt"):
line = line.split()
num_list1.append(line)
print(num_list1) # this is printing my list perfect
# ['15,57,14,33,72,79,26,56,42,40'] is what
# prints, which is what im looking for
temp = num_list1[0] # this is where im running into issues
num_list1[0] = num_list1[2]
num_list1[2] = temp
print(num_list1)
全行存儲在兩個引號之間的位置[0]。 這就是為什么您沒有索引[2]的原因。 您可以通過打印num_list1 [2]進行測試。
print num_list1[2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-8965836976ae> in <module>()
10 #num_list1[2] = temp
11 print(num_list1)
---> 12 print num_list1[2]
IndexError: list index out of range
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.