【问题标题】:PYTHON: Doesn't increment position of a list elementPYTHON:不增加列表元素的位置
【发布时间】:2018-05-09 21:41:47
【问题描述】:
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!  

大家好;我有一个问题,为什么程序在前 3 次迭代时返回 0 表示 sq?它不应该给我0、1、2..吗?在过去的 2 天里,我无法绕开它......

【问题讨论】:

  • 1[1, 1, 1] 中的第一个索引是什么?
  • 您正在搜索列表中第一次出现的1。为什么你期望它返回 0 以外的东西?您从文档中看不懂什么?
  • 您可以在此处阅读有关列表函数的更多信息:docs.python.org/2/tutorial/datastructures.html

标签: python list iteration


【解决方案1】:

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

【讨论】:

  • 啊啊啊..我没有意识到这一点。谢谢!
【解决方案2】:

因为您有 3 个“1”,如果您尝试使用不同的数据,它会显示第一个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多