簡體   English   中英

如果列表 Python 中存在元素,如何從列表中刪除元素

[英]How to remove element from list if element is present in list 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)

樣品 output:

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

所需的 output:

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

列表的元素不是字符串。 它們是 bs4.element 的實例。 class。 你必須像這樣比較它:

title_list = []
for t in titles:
    title_list.append([])
    for c in t.contents:
        if c.string != None:
            title_list[-1].append(c) # or c.string if you need only names

.string of </br>None ,其他的就是你在 output 中看到的。

在這種情況下.strings.stripped_strings應該優先於.contents

所以改變

for t in titles:
    title_list.append(t.contents)

for t in titles:
    title_list.append(list(t.stripped_strings))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM