从列表中提取最长的子序列。无法找出TypeError

时间:2016-11-27 13:26:50

标签: python python-3.x typeerror

我有一个任务,我需要在列表中找到最长的子序列。我在python

中创建了这个函数
def subSequence(sequence):

    newSequence = [0]
    longest = [0]

    for x in range(0,len(sequence)):
        print("x is " +str(x)+"\n")
        if sequence[x] == sequence[0]:
            newSequence.append(sequence[x])

        elif sequence[x] > sequence[x-1]:
            print("sequence[x] = " +str(sequence[x]))
            print("sequence[x-1] = " +str(sequence[x-1]))
            newSequence.append(sequence[x])

        else:
            if longest <= newSequence:
                del longest[:]
                longest.append(newSequence[:])
                print("longest = "+str(longest))
                del newSequence[:]
                newSequence.append(sequence[x])
            else:
                del newSequence[:]

    return newSequence

mySequence = [1,2,3,2,5,6,7,2]
print(subSequence(mySequence))

这一切都有效,直到我将最后2添加到mySequence变量中,现在我收到此错误

Traceback (most recent call last):
  File "D:/Calum/Desktop/subSequence.py", line 27, in <module>
    print(subSequence(mySequence))
  File "D:/Calum/Desktop/subSequence.py", line 15, in subSequence
    if longest <= newSequence:
TypeError: unorderable types: list() <= int()

我不太确定如何添加2会导致类型错误发生

输出应为2,5,6,7,因为它是按升序排列的最长数字序列

1 个答案:

答案 0 :(得分:1)

这一行:

          longest.append(newSequence[:])

似乎要将一个列表附加到longest,请执行以下操作:

          longest.extend(newSequence[:])