简体   繁体   中英

How to swap numbers read from a list .txt file? Error “list index out of range”

What I am trying to do is read from a .txt file containing numbers, then from that list swap 2 of the numbers into different places(index's) in the list. From what I can tell the issue is that the list is being appended, my index's are no longer correct. How can I fix this so I won't get my "list index out of range" error.

Assignment Task:Your job in this assignment is to create a simple numerical dataset. Collect that data from an external file and then run through the sorting strategy we looked at, swapping.

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)

You need to split based on space. Use split() instead of strip(). The strip() method returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Whereas split() : Split a string into a list where each word is a list item.

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)

The full line is getting stored at place [0] between two quotes. Thats why you are getting out of index for [2]. You can test this by printing 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM