【问题标题】:Not enough values to unpack in Python没有足够的值在 Python 中解包
【发布时间】:2018-08-25 11:48:28
【问题描述】:

我试图让用户在 Python 中操作列表。

number_of_commands = int(input())
x = 0
my_list = []
while x <= number_of_commands:
    command, i, e = input().split(' ')
    command = str(command)
    i = int(i)
    e = int(e)
    x = x + 1

    if command == 'insert':
        my_list.insert(i, e)
    elif command == 'print':
        print(my_list)
    elif command == 'remove':
        my_list.remove(e)
    elif command == 'append':
        my_list.append(e)
    elif command == 'sort':
        my_list.sort()
    elif command == 'pop':
        my_list.pop()
    elif command == 'reverse':
        my_list.reverse()
    else:
        print("goodbye")

当用户输入需要两个整数的命令(例如insert)时,程序可以运行,但是当用户输入print 之类的内容时,我收到错误“没有足够的值来解压”。仅当您将其输入为 print 0 0 时才有效。如何允许用户输入带整数和不带整数的命令?

【问题讨论】:

  • 看看Python的内置range函数。根据定义,知道迭代次数的循环更适合for 循环而不是whilefor x in range(number_of_comands): 将允许您同时删除 x = 0x = x + 1 行。另外x = x + 1 通常写成x += 1

标签: python python-3.x


【解决方案1】:

你可以使用

command, *values = input().split(' ')

values 是一个列表。例如“插入”部分变为:

if command == 'insert':
    my_list.insert(int(values[0]), int(values[1]))

【讨论】:

【解决方案2】:
def my_function(command='print', i=0, e=0):
    # your function code here

user_input = input().split(' ')
if len(user_input) > 3:
    print('usage : function i e')
else:
    my_function(*user_input)

在列表将列表转换为函数的参数之前使用*

使用函数是一种很好的方式来获得默认值,以防它们未定义。

【讨论】:

    【解决方案3】:

    这里是拆包的地方:

    command, i, e = input().split(' ')
    

    仅输入“print”将不允许此行正确执行,因为没有提供 i 和 e 的值。

    所以只需读取输入,然后将其拆分并检查用户提供了多少参数:

    input_str = input()
    input_str_split = input_str.split(' ')
    if len(input_str_split) == 3:
        command, i, e = input_str_split
        i = int(i)
        e = int(e)
    else:
        command = input_str_split
    

    【讨论】:

      【解决方案4】:

      出现此错误是因为您总是希望命令有 3 个输入:

      command, i, e = input().split(' ')
      

      当您使用仅打印时会发生这种情况:

      >>> "print".split(' ')
      ['print']
      

      所以input.split() 的输出是一个只有一个元素的列表。然而:

      command, i, e = input().split(' ')
      

      需要 3 个元素:commandie

      其他答案已经向您展示了如何解决修改代码的问题,但是随着您添加更多命令,它会变得非常笨拙。您可以使用 Python 的原生 REPL 并创建自己的提示符。 (Original post where I read about the cmd module)

      from cmd import Cmd
      
      class MyPrompt(Cmd):
          my_list = []
      
          def do_insert(self, *args):
              """Inserts element in List"""
              self.my_list.append(*args)
      
          def do_print(self, *args):
              print(self.my_list)
      
          def do_quit(self, args):
              """Quits the program."""
              raise SystemExit
      
      
      if __name__ == '__main__':
          prompt = MyPrompt()
          prompt.prompt = '> '
          prompt.cmdloop('Starting prompt...')
      

      例子:

      $ python main.py
      Starting prompt...
      > insert 2
      > insert 3
      > insert 4
      > print
      ['2', '3', '4']
      > 
      

      cmd 还允许您记录代码,因为我没有为 print 创建文档字符串,这是我在终端中键入 help 后显示的内容:

      > help
      
      Documented commands (type help <topic>):
      ========================================
      help  insert  quit
      
      Undocumented commands:
      ======================
      print
      

      我把添加其他命令和一个有趣的练习留给你。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 2023-02-23
        • 2021-07-16
        • 1970-01-01
        • 2018-01-26
        相关资源
        最近更新 更多