PYTHON:不会增加列表元素

时间:2018-05-09 21:41:48

标签: python list iteration

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!  
嘿,伙计们我有一个问题为什么程序会给我0平方,反之前的3次?难道不能给我0,1,2 ......?在过去的两天里,我无法绕过它...

2 个答案:

答案 0 :(得分:4)

因为sequence2.index(value)会返回'值'的第一个实例。 ,你在序列2中重复了1次

答案 1 :(得分:1)

因为你有3个'1'并且如果你尝试使用不同的数据它会显示第一个