如何将列表中的空项更改为N/a值?

2024-04-20 03:12:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题。我正在使用BeautifulSoup抓取一个webppage,我正在查找表中的所有内容,以便将它们放入列表中,但问题是,当我找不到图像标记时,我需要列表中的值“N/a”。现在列表元素为空

这是我的代码:

cards = []

for row in TR_HP1_3[0:11]:
       cards.append([image.get('title') for image in row.find_all('img')])

print(cards)

for x in cards:
     cards_corrected = [x if x != None else "N/a" for x in cards]

print(cards_corrected)

这为我提供了以下输出:

[[], [], [], ['geelrode kaart'], [], [], [], [], [], [], []]
[[], [], [], ['geelrode kaart'], [], [], [], [], [], [], []]

如何将这些空值更改为N/a


Tags: 代码in图像image内容列表forrow
1条回答
网友
1楼 · 发布于 2024-04-20 03:12:49

改变

cards.append([image.get('title') for image in row.find_all('img')])

与:

cards.append([image.get('title') if image.get('title') else "N/a" 
              for image in row.find_all('img')])

相关问题 更多 >