String python 3中insert语句中的变量问题

String python 3中insert语句中的变量问题,string,list,variables,insert,python-3.6,String,List,Variables,Insert,Python 3.6,这是关于黑客银行的问题。下面是我的实现代码。我面临insert语句的问题,因为它要求至少两个变量。我尝试将用户输入转换为列表,然后输入到insert语句中。这是一个错误。请帮忙 if __name__ == '__main__': N = int(input()) l=[] for _ in range(N): line = input().split() cmd = line[0] args= line[1:]

这是关于黑客银行的问题。下面是我的实现代码。我面临insert语句的问题,因为它要求至少两个变量。我尝试将用户输入转换为列表,然后输入到insert语句中。这是一个错误。请帮忙

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)

在列表中插入

Insert用于在列表的特定索引处插入给定值。它需要两个论点

python.org中的定义:

在给定位置插入项目。第一个参数是 要插入的元素,因此a.insert(0,x)在 列表的前面,a.insert(len(a),x)相当于 a、 附加(x)


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

  • 索引
  • 项目
  • 在这个问题中,您必须根据输入获取索引

    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()
    
    此代码将解决您的问题