簡體   English   中英

從python列表中刪除所有'#'

[英]Remove all the '#' from a list in python

在這方面,我嘗試了各種不同的方法。 我如何從創建的列表中刪除所有#號?

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
page = requests.get('http://www.demodms.com/annuity', headers=headers)
soup = BeautifulSoup(page.text, 'html.parser')
lists = []

for anchor in soup.find_all("a"):
    lists.append(anchor['href'])

lists.remove('#')


print(lists)

.remove(value)僅刪除第一個匹配項。 您可以使用循環來刪除重復的值,直到沒有剩余值為止:

while '#' in lists:
    lists.remove('#')

也許更好的解決方案是首先不要添加不需要的值:

for anchor in soup.find_all("a"):
    if anchor['href'] != '#':
        lists.append(anchor['href'])

或列表理解:

print([i for i in lists if i != '#'])

filter

print(list(filter(lambda x: x!='#',lists)))

就像約翰·戈登所說的,甚至更容易:

for anchor in soup.find_all("a"):
    if anchor['href'] != '#':
        lists.append(anchor['href'])

或再次理解列表:

lists = [anchor['href'] for anchor in soup.find_all("a") if anchor['href'] != '#']

請參閱清單說明

請參見貼圖,過濾和縮小

刪除字符所有實例的一種快速方法是字符串方法replace

假設這樣的列表,根據您的反饋進行更新。 假設刪除字符串中的所有#* ,則只需使用一次replace:

a = ['#AA#andRou**nds', '#abcDrat', '#ad**dchat', '#advchat', '#Aet#', '#A#Cha#t', 
    '#An#Q', '#an#alk', '#AskAvail#', '#ASP#hat', '#AT#lk', 
    '#aut#chat', '#AX###hat', '#aya#m', '#*bc*#c#', '#bc#w', '#bioet##hx']

a = [e.replace("#", "").replace("*", "") for e in a]
print(a)

這將使用列表理解來遍歷列表的每個元素,並刪除每個字符串中所有#實例。 如果要限制替換的e.replace("#", "", 1)標簽數量,則可以發送可選計數(例如,如果僅想刪除第一個實例, e.replace("#", "", 1)改為e.replace("#", "", 1) )。

暫無
暫無

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

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