如何交换从列表 .txt 文件中读取的数字?错误 "list index out of range"

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

我想做的是从包含数字的 .txt 文件中读取,然后从该列表中将 2 个数字交换到列表中的不同位置(索引)。据我所知,问题是正在附加列表,我的索引不再正确。我该如何解决这个问题,这样我就不会收到 "list index out of range" 错误。

作业 Task:Your 此作业中的作业是创建一个简单的数值数据集。从外部文件收集数据,然后 运行 通过我们查看的排序策略,交换。

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)

您需要根据 space 拆分。使用 split() 而不是 strip()。 strip() 方法 returns 删除了前导字符和尾随字符的字符串副本(基于传递的字符串参数)。而 split() :将一个字符串拆分为一个列表,其中每个单词都是一个列表项。

open_list = 打开("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