ValueError: too many values to unpack (expected 2) with a list of tuples in Python
ValueError: too many values to unpack (expected 2) with a list of tuples in 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))
您已经使用 map
遍历列表。分析函数中的 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))
我在使用 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))
您已经使用 map
遍历列表。分析函数中的 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))