python - 如果列表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
。
解决方案
也许您可以尝试仅将对象附加到字符串的 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)
推荐阅读
- python-2.7 - Scapy --TypeError: unbound 方法 copy() 必须以 UDP 实例作为第一个参数调用
- java - 强制执行打印顺序,但线程在一次迭代后相互等待
- c++ - 不能在 Xcode 中对 c++ 项目多次使用 I/O
- xcode10 - Branch.io 未在 xcode 10 上显示传递的值(读取链接不起作用)
- html - 如何在 Bootstrap-vue 或 Bootstrap 4 的输入组左侧添加 Font Awesome 图标?
- javascript - 如何在 1 分钟后停止 setTimeout,每 1 秒重复一次
- azure - Azure Pipelines:加载 YAML 构建管道时出错:段数错误
- java - 像标签一样的 JLabel
- ruby-on-rails - Rails 控制台找不到设计 reset_password_token(调试“重置密码令牌无效”)
- excel - VBA Range.Copy转置粘贴1004错误