【问题标题】:Can you explain me why outpot is so?你能解释一下为什么outpot会这样吗?
【发布时间】:2022-11-01 21:45:25
【问题描述】:

if __name__ == '__main__':
    N = int(input())
    lst = []
    nums = []
        
    for i in range(N):
        a = input()
        temp = a.split()
        if 'insert' in temp:
            lst.insert(int(temp[1]), int(temp[2]))
        elif 'print' in temp:
            nums.append(lst)
        elif 'remove' in temp:
            del lst[lst.index(int(temp[1]))]
        elif 'append' in temp:
            lst.append(int(temp[1]))
        elif 'sort' in temp:
            lst.sort()
        elif 'pop' in temp:
            lst.pop(-1)
        elif 'reverse' in temp:
            lst = lst.reverse()
    for i in nums:
        print(i)

输入

    12

    insert 0 5

    insert 1 10

    insert 0 6

    print

    remove 6

    append 9

    append 1

    sort

    print

    pop

    reverse

    print

输出

    [9, 5, 1]

    [9, 5, 1]

    None

预期产出

    [6, 5, 10]

    [1, 5, 9, 10]

    [9, 5, 1]

我在 HackerRank 上做任务,我几乎已经完成了,但是突然在“for i in range(N)”程序的每个循环中添加最后一个列表三次独立于输入。

我已经尝试了很多调试测试,但在我的脚本中找不到错误。

【问题讨论】:

  • 在第一个 for 循环的末尾添加 print(lst)print(nums),你就会看到发生了什么。当您编辑lst 时,nums 会随之改变

标签: python


【解决方案1】:

列表的 reverse() 方法返回 None,它只是简单地反转原始列表。对于完整的解决方案,您还需要了解可变和不可变对象。

# Current
elif 'reverse' in temp:
    lst = lst.reverse()

# it should be
elif 'reverse' in temp:
    lst.reverse()

【讨论】:

    【解决方案2】:

    需要改变的两件事:

    1. lst.reverse() 而不是 lst = lst.reverse()
    2. 当您对lst 进行附加、删除等操作时,您保存在nums 中的列表将随之更改。您需要使用nums.append(lst.copy()) 而不是nums.append(lst)

      完整代码变为:

      if __name__ == '__main__':
          N = int(input())
          lst = []
          nums = []
      
          for i in range(N):
              a = input()
              temp = a.split()
              if 'insert' in temp:
                  lst.insert(int(temp[1]), int(temp[2]))
              elif 'print' in temp:
                  nums.append(lst.copy())
              elif 'remove' in temp:
                  del lst[lst.index(int(temp[1]))]
              elif 'append' in temp:
                  lst.append(int(temp[1]))
              elif 'sort' in temp:
                  lst.sort()
              elif 'pop' in temp:
                  lst.pop(-1)
              elif 'reverse' in temp:
                  lst.reverse()
      
          for i in nums:
              print(i)
      

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 2021-10-17
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多