简体   繁体   English

如何交换从列表.txt文件读取的数字? 错误“列表索引超出范围”

[英]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. 我想做的是从包含数字的.txt文件中读取内容,然后从该列表中将数字2交换到列表中的不同位置(索引)。 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(). 使用split()代替strip()。 The strip() method returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). strip()方法返回字符串的副本,该字符串的开头和结尾字符均被删除(基于传递的字符串参数)。 Whereas split() : Split a string into a list where each word is a list item. 而split():将字符串分割成一个列表,其中每个单词都是一个列表项。

open_list = open("my_list.txt") 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. 全行存储在两个引号之间的位置[0]。 Thats why you are getting out of index for [2]. 这就是为什么您没有索引[2]的原因。 You can test this by printing num_list1[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.

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