samedi 1 août 2020

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 outputted 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'}) return empty and the compiler return 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 return an error

ValueError: not enough values to unpack (expected 2, got 0)

Nevertheless, the following code work despite in some occasion the all_td.find_all('a', {'class': 'ddmDocTitle'}) return 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'}
                      ))

Aucun commentaire:

Enregistrer un commentaire