小编Cor*_*iux的帖子

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

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

这是我在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.我究竟做错了什么?我应该使用除元组以外的其他东西吗?这是我的迭代不好吗?

python iteration nested tuples

3
推荐指数
1
解决办法
1403
查看次数

标签 统计

iteration ×1

nested ×1

python ×1

tuples ×1