得到错误:“没有足够的值要解压"使用Python的列表理解返回两个输出时 [英] Getting Error: "not enough values to unpack" when returning two outputs using list comprehension with Python
本文介绍了得到错误:“没有足够的值要解压"使用Python的列表理解返回两个输出时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是创建一个输出两个值的列表理解.
The objective is to create a list comprehension that outputted two values.
for循环如下所示
paper_href_scopus = []
paper_title = []
for litag in all_td.find_all('a', {'class': 'ddmDocTitle'}):
paper_href_scopus.append(litag['href'])
paper_title.append(litag.text)
在按以下方式创建列表理解时,不会出现任何错误
While creating list comprehension as below work without any error
[(paper_href_scopus.append(litag['href']), paper_title.append(litag.text)) \
for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})]
如下修改列表理解:
paper_href_scopus, paper_title = [(litag['href'], litag.text) \
for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})]
导致错误:
ValueError:没有足够的值可解包(预期2,得到1)
ValueError: not enough values to unpack (expected 2, got 1)
我可以知道如何避免这种错误吗?
May I know how such an error can be avoided?
推荐答案
您可以只使用 zip
之类的
>>> paper_href_scopus, paper_title = zip(*[(litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})])
此外,无需在内部创建 list
,您可以使用 genexpr
,但是我认为这并不重要.没什么:
Also, no need to create the list
inside, you can use a genexpr
, but i don't think it will matter here. Neverthless:
>>> paper_href_scopus, paper_title = zip(*((litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})))
注意:
根据 balandongiv 的建议,这是文档
As suggested by balandongiv, here's a link to genexpr
usage and another link to official docs
这篇关于得到错误:“没有足够的值要解压"使用Python的列表理解返回两个输出时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文