我正在编写一个 mergesort3 函数,它应该接受一个数字或值数组并将它们分成 3 个单独的数组进行排序
I am writing a mergesort3 function that is supposed to take an array of numbers or values and divide them into 3 separate arrays for sorting
我的代码有问题,因为它不会执行并以以下格式显示 TypeError
消息:
list indices must be integers or slices, not list
.
我相信我的归并排序函数可以正常工作,但我不完全确定。
我认为问题出在我试图从包含未排序数字列表的文件中读取的代码部分。
with open(filelocation) as fl:
line = fl.readline()
while line:
line = line.split()
for i in range(1, len(line)):
# converting read elements into integer values for sorting
line[i] = int(line[i])
input.append(line)
line = fl.readline()
with open('merge3.txt', 'w') as f:
for i in input:
mergeSort3(input[i], 0, 1 / 3 * len(input), 2 / 3 * len(input), len(input), input())
print(input)
此代码的最后两行弹出错误,或者更确切地说,当我调用初始函数的参数时 mergeSort3
语句:def mergeSort3(arr1, low, mid1, mid2, high, arr2)
。
我也在 Python 中编写我的代码,尽管这可能不是问题所在。
感谢您的帮助!
基本上我期望的是能够打开文件 data.txt 并读取每个值,然后通过合并排序 /3(将数组分成三分之一)对数据进行排序并写入将该数据放入名为 merge3.txt.
的新文本文件中
当您将 line
附加到 input
时,line
是一个整数列表。因此,input
是列表的列表。
当您遍历 input
时,i
将是这些列表之一。
然后您尝试使用该列表索引 input
。因此错误告诉您不能使用列表作为索引。
我的代码有问题,因为它不会执行并以以下格式显示 TypeError
消息:
list indices must be integers or slices, not list
.
我相信我的归并排序函数可以正常工作,但我不完全确定。 我认为问题出在我试图从包含未排序数字列表的文件中读取的代码部分。
with open(filelocation) as fl:
line = fl.readline()
while line:
line = line.split()
for i in range(1, len(line)):
# converting read elements into integer values for sorting
line[i] = int(line[i])
input.append(line)
line = fl.readline()
with open('merge3.txt', 'w') as f:
for i in input:
mergeSort3(input[i], 0, 1 / 3 * len(input), 2 / 3 * len(input), len(input), input())
print(input)
此代码的最后两行弹出错误,或者更确切地说,当我调用初始函数的参数时 mergeSort3
语句:def mergeSort3(arr1, low, mid1, mid2, high, arr2)
。
我也在 Python 中编写我的代码,尽管这可能不是问题所在。
感谢您的帮助!
基本上我期望的是能够打开文件 data.txt 并读取每个值,然后通过合并排序 /3(将数组分成三分之一)对数据进行排序并写入将该数据放入名为 merge3.txt.
的新文本文件中当您将 line
附加到 input
时,line
是一个整数列表。因此,input
是列表的列表。
当您遍历 input
时,i
将是这些列表之一。
然后您尝试使用该列表索引 input
。因此错误告诉您不能使用列表作为索引。