出现错误:在Python中使用列表理解和条件语句时“没有足够的值要解压" [英] Getting Error: 'not enough values to unpack' when using list comprehension together with conditional statement in Python
问题描述
目标是创建一个输出两个值的列表理解.
The objective is to create a list comprehension that outputs 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)
根据 OP 的建议,可以通过
paper_href_scopus, paper_title = zip(*[(litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})])
但是,在某些情况下,all_td.find_all('a', {'class': 'ddmDocTitle'})
返回empty
并且编译器返回错误:
However, there is an instances where the all_td.find_all('a', {'class': 'ddmDocTitle'})
returns empty
and the compiler returns an error:
ValueError:没有足够的值可解包(预期2,得到0)
ValueError: not enough values to unpack (expected 2, got 0)
基于此线程中的讨论,似乎上面的代码可以修改为
Based on the discussion in this thread, it seems the above code can be modified as
paper_href_scopus, paper_title = zip(
*((litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'}) \
if all_td.find_all('a', {'class': 'ddmDocTitle'}
))
但是,编译器仍然返回错误
But still, the compiler returns an error
ValueError:没有足够的值可解包(预期2,得到0)
ValueError: not enough values to unpack (expected 2, got 0)
尽管如此,以下代码仍然有效,尽管在某些情况下all_td.find_all('a', {'class': 'ddmDocTitle'})
返回empty
Nevertheless, the following code works despite the fact that on some occasions the all_td.find_all('a', {'class': 'ddmDocTitle'})
returns empty
[(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=[]
,因此我想避免使用append.
But, I would like to avoid using append as there is requirement to initialize paper_href_scopus=[]
and paper_title=[]
beforehand.
我可以知道如何解决该代码吗?
May I know, what can I do to fix the code?
paper_href_scopus, paper_title = zip(
*((litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'}) \
if all_td.find_all('a', {'class': 'ddmDocTitle'}
))
推荐答案
首先,带有if
的版本基本上等同于:
Firstly, the version with the if
is basically equivalent to:
tmp = []
for litag in all_td.find_all('a', {'class': 'ddmDocTitle'}):
if all_td.find_all('a', {'class': 'ddmDocTitle'}):
tmp.append((litag['href'], litag.text))
paper_href_scopus, paper_title = zip(*tmp)
如果您的文档有100个匹配元素,它将进行101次搜索.
which, if your document has 100 matching elements, it does 101 searches.
这是我的建议:忘记zip
.相反,请分拆一下代码:
Here's my proposal: forget about the zip
. Instead, split out the code a bit:
litags = all_td.find_all('a', {'class': 'ddmDocTitle'})
paper_href_scopus = [litag['href'] for litag in litags]
paper_title = [litag.text for litag in litags]
这篇关于出现错误:在Python中使用列表理解和条件语句时“没有足够的值要解压"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!