首页 > 解决方案 > 如果列表Python中存在元素,如何从列表中删除元素

问题描述

如果元素存在于列表中,我有一个列表列表,我试图从每个列表中删除一个元素。

代码:

import requests
from bs4 import BeautifulSoup

# get link and parse
page = requests.get('https://www.finviz.com/screener.ashx?v=111&ft=4')
soup = BeautifulSoup(page.text, 'html.parser')

print('List of filters\n')

# return 'Title's for each filter
titles = soup.find_all('span', attrs={'class': 'screener-combo-title'})
title_list = []
for t in titles:
    title_list.append(t.contents)

print(title_list)

样本输出:

[['Price/Free Cash Flow'], ['EPS growth', <br/>, 'this year'], ['EPS growth', <br/>, 'next year']]

期望的输出:

[['Price/Free Cash Flow'], ['EPS growth', 'this year'], ['EPS growth', 'next year']]

我遇到的问题是我检查元素是否存在的检查不起作用。我试过if '<br/>' in whatever:whatever.remove('<br/>'). NoneType is non callable. 我看到我<br/>作为字符串输入,但我也看到它不是列表中的字符串。我试过放弃'',然后又回来了unresolved reference。我尝试检查每个列表是否有多个元素,如果有,则删除第二个元素,但它也回来了NoneType is non callable

标签: python

解决方案


也许您可以尝试仅将对象附加到字符串的 isinstance :

for t in titles:
    title_sublist=[] 
    for content in t.contents:
        if isinstance(content, str) :
            title_sublist.append(content)
    title_list.append(title_sublist)

推荐阅读