使用python合并排序,列表索引超出范围

时间:2018-02-12 17:53:54

标签: python list mergesort

enter image description here我正在尝试按如下方式对文本文件进行排序:

afsdgf(姓名)34(商标)

asdsad 45

erttre 56

....这样的2000条记录

我得到的IndexError如下:

 if int(record_list[h][1]) >= int(record_list[j][1]):
 IndexError: list index out of range

以下是代码:

import sys


def merge_sort(low, high):
    if low < high:
        mid = int((low + high) / 2)
        merge_sort(low, mid)
        merge_sort(mid + 1, high)
        merge(low, mid, high)


def merge(low, mid, high):
    duplicate_list = []
    global record_list
    h = low
    j = mid + 1
    while h <= mid and j <= high:
        if int(record_list[h][1]) >= int(record_list[j][1]): #problem
            duplicate_list.append(record_list[h])
            h += 1
        else:
            duplicate_list.append(record_list[j])
            j += 1

    if h > mid:
        while j <= high:
            duplicate_list.append(record_list[j])
            j += 1
    else:
        while h <= mid:
            duplicate_list.append(record_list[h])
            h += 1

    record_list = duplicate_list.copy()


sys.setrecursionlimit(1500)


myFile = open("C:\TurboC++\Disk\TurboC3\BIN\sample.txt", encoding="utf-8", 
mode="r")
record_list = []

while True:
    line = myFile.readline()
    if not line:
        break
    record_list.append(line.split())
merge_sort(0, 500)

print(record_list)

我刚开始使用python,帮助。

0 个答案:

没有答案