sequence = [1, 1, 1, 2, 3]

sequence2 = []
k = 0
if len(sequence) == 2 or len(sequence) == 1:
    print('Great!')
else:
    for element in range(0, (len(sequence))):
        sequence2.append(sequence[element])
        sq = sequence2.index(sequence2[-1])
        print(sequence2, sq)
        if sequence2 == sorted(sequence2):
            print('This is good thus far:', sequence2)
        else:
            print(sequence2[sq-1], sequence2[sq])
            print(sequence2.index(sequence2[-1]))
            if sequence2[sq-1] >= sequence2[sq]:
                sequence2.pop(sequence2.index(sequence2[sq - 1]))
                print('We poppoed an element')
                print(sequence2)
                k = k+1
if k >= 2:
    print(sequence2)
    print('This doesnt work')
else:
    print('Works properly!')

输出:
[1] 0
This is good thus far: [1]
[1, 1] 0
This is good thus far: [1, 1]
[1, 1, 1] 0
This is good thus far: [1, 1, 1]
[1, 1, 1, 2] 3
This is good thus far: [1, 1, 1, 2]
[1, 1, 1, 2, 3] 4
This is good thus far: [1, 1, 1, 2, 3]
Works properly!

嘿,伙计们,我有一个问题,为什么程序会在sq迭代的前3次返回0?它不应该给我0,1,2。。?在过去的两天里,我无法控制自己的情绪。。。

最佳答案

因为sequence2.index(value)返回“value”的第一个实例,并且在sequence2中重复了1

10-06 16:01