如何在python中解压缩嵌套元组?

Cor*_*iux 3 python iteration nested tuples

假设我有用户(约翰,安娜)可以按自己选择的数量订购水果(橙子,苹果).

这是我在python中所做的:

orders = (('John', (('apples', 3), ('oranges', 1))),
          ('Anna', (('oranges', 6))))
Run Code Online (Sandbox Code Playgroud)

我想迭代订单:

for user, order in orders:
    for fruit, quantity in order:
        print "%s wants %d %s" % (user, quantity, fruit)
Run Code Online (Sandbox Code Playgroud)

这是我期待的输出:

John wants 3 apples
John wants 1 oranges
Anna wants 6 oranges
Run Code Online (Sandbox Code Playgroud)

我得到了ValueError: too many values to unpack.我究竟做错了什么?我应该使用除元组以外的其他东西吗?这是我的迭代不好吗?

Dan*_*man 7

显示确切的追溯将是有用的.

错误只是安娜的命令实际上不是嵌套元组:它是一个简单的元组.你最后错过了一个逗号:

orders = (('John', (('apples', 3), ('oranges', 1))),
          ('Anna', (('oranges', 6),)))
#                                 ^ here
Run Code Online (Sandbox Code Playgroud)

记住它是制作元组的逗号,而不是括号.

正如其他人所说,嵌套的dicts在这里更合适.