ValueError:太多的值无法用Python中的元组列表解包(预期为2个)

2024-05-23 16:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Python创建代码时遇到了这个问题。我传递了一个元组列表,但在解包后使用map函数,然后使用列表时。我得到这个错误:

ValueError:要解包的值太多(预计2个)

你知道如何克服这个问题吗?我找不到与元组列表相关的合适答案:-(

这是密码

stock_markets = [('AAPL','200'),('MSFT','780'),('ORCL','650'),('CISC','350')]

def analyze_stocks(stock_markets):
    current_max = 0
    stock_name = ''

    for company,price in stock_markets:
        if int(price) > current_max:
            current_max = int(price)
            stock_name = company
        else:
            pass

    return (stock_name, current_max)

list(map(analyze_stocks,stock_markets))

Tags: 函数代码namemap列表stockcurrentprice
1条回答
网友
1楼 · 发布于 2024-05-23 16:58:22

您已经在使用map对列表进行迭代。不需要在analyze函数中使用for循环(因为您正在使用map逐个传递股票),这是错误的根源。正确的版本应该是这样的:

stock_markets = [('AAPL','200'),('MSFT','780'),('ORCL','650'),('CISC','350')]

def analyze_stocks(stock_markets):
    current_max = 0
    stock_name = ''

    company, price = stock_markets
    if int(price) > current_max:
        current_max = int(price)
        stock_name = company

    return (stock_name, current_max)

list(map(analyze_stocks,stock_markets))

相关问题 更多 >