ValueError: too many values to unpack (expected 2)

发布时间:2024年01月17日

1. 错误信息

Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-f12639514596>", line 1, in <module>
    meanU, np_subdf = Trans3D(np_subdf_ori)
ValueError: too many values to unpack (expected 2)

2. 原因分析

2.1 Cause 1: List Unpacking

appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2 = appliances

OUT:

ValueError                                Traceback (most recent call last)
<ipython-input-4-2c62c443595d> in <module>
      1 appliances = ['Fridge', 'Microwave', 'Toaster']
----> 2 appliance_1, appliance_2 = appliances

ValueError: too many values to unpack (expected 2)

Solution

appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2, appliance_3 = appliances

2.2 Unpacking Function Returns

def compute(x, y): 
    sum = x + y
    product = x * y
    quotient = x / y
    return sum, product, quotient

result_1, result_2 = compute(12, 5)

OUT:

ValueError                                Traceback (most recent call last)
<ipython-input-5-9e571b686b4f> in <module>
      6     return sum, product, quotient
      7 
----> 8 result_1, result_2 = compute(12, 5)

ValueError: too many values to unpack (expected 2)

Solution 1
First we’ll define the function once more:

def compute(x, y): 
    sum = x + y
    product = x * y
    quotient = x / y
    return sum, product, quotient
result_1, result_2, result_3 = compute(12, 5)

Solution 2
Using a underscore to throw away a return value:

result_1, result_2, _ = compute(12, 5)
文章来源:https://blog.csdn.net/weixin_46713695/article/details/135641163
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。