【问题标题】:Issue with variables in insert statement in python 3python 3中插入语句中的变量问题
【发布时间】:2018-06-15 03:04:49
【问题描述】:

这是关于hackerrank问题https://www.hackerrank.com/challenges/python-lists/problem。下面是我实现的代码。我面临插入语句的问题,因为它要求至少两个变量。我尝试将用户输入转换为列表,然后输入到插入语句中。它抛出一个错误。请帮忙!

if __name__ == '__main__':
    N = int(input())
    l=[]
    for _ in range(N):
        line = input().split()
        cmd = line[0]
        args= line[1:]
        """if cmd!= "print":
            cmd += "(" + ",".join(args)+")"""
        x = ",".join(map(str,args))
        if cmd == "insert":
            l.insert(x)
        elif cmd == "remove":
            l.remove(x)
        elif cmd == "append":
            l.append(x)
        elif cmd == "sort":
            l.sorted(x)
        elif cmd == "pop":
            l.pop(x)
        elif cmd =="reverse":
            l.reverse(x)
        else:
            print(l)

【问题讨论】:

    标签: string list variables insert python-3.6


    【解决方案1】:

    插入列表:

    插入用于insert 列表特定索引处的给定值。它需要两个参数。

    来自 python.org 的定义:

    在给定位置插入一个项目。第一个参数是索引 要插入之前的元素,因此 a.insert(0, x) 插入 列表的前面,a.insert(len(a), x) 等价于 a.append(x)。

    【讨论】:

      【解决方案2】:

      这是抛出错误,因为 Insert 方法只有一个参数没有重载。 Insert 方法有一个带有两个参数的重载,

      1. 索引
      2. 项目

      在问题中,你必须根据输入来获取索引。

      if __name__ == '__main__':
          n = int(input())
          list = []
          for i in range(n):
              userinput = input().strip().split()
              cmd = userinput[0]
              if(len(userinput) == 3):
                  index = int(userinput[1])
                  val = int(userinput[2])
              elif(len(userinput) == 2):
                  val = int(userinput[1])
      
              if(cmd == 'insert'):
                  list.insert(index, val)
              elif(cmd == 'append'):
                  list.append(val)
              elif(cmd == 'print'):
                  print(list)
              elif(cmd=='remove' and val in list):
                  list.remove(val)
              elif(cmd=='pop' and len(list) > 0):
                  list.pop()
              elif(cmd=='reverse'):
                  list = list[::-1]
              elif(cmd=='sort'):
                  list.sort()
      

      此代码将解决您的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-21
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多