Getting Error: 'not enough values to unpack' when using list comprehension together with conditional statement in Python

谁说胖子不能爱 提交于 2020-08-05 06:17:27

问题


The objective is to create a list comprehension that outputs two values.

The for loops look like below

    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)

As suggested by OP, this can be achieved by

    paper_href_scopus, paper_title = zip(*[(litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})])

However, there is an instances where the all_td.find_all('a', {'class': 'ddmDocTitle'}) returns empty and the compiler returns an error:

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: not enough values to unpack (expected 2, got 0)

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'})]

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'}
                          ))

回答1:


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)

which, if your document has 100 matching elements, it does 101 searches.

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]


来源:https://stackoverflow.com/questions/63204196/getting-error-not-enough-values-to-unpack-when-using-list-comprehension-toget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!