从Python列表中删除字符时的不同输出

2024-04-26 22:18:23 发布

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

我正在用python做一些web抓取,我想从列表的每个元素中删除“.”元素。我有两种方法,但只有一种给出正确的输出。代码在上面

import urllib2
from bs4 import BeautifulSoup
first=urllib2.urlopen("http://www.admision.unmsm.edu.pe/res20130914/A.html").read()
soup=BeautifulSoup(first)
w=[]
for q in soup.find_all('tr'):
    for link in q.find_all('a'):
        w.append(link["href"])

s = [ i.replace(".","") for i in w ]

l=[]

for t in w:
    l=t.replace(".","")

如果我运行print s,输出就是正确的输出,但是如果我运行print l,它就不是

我想知道为什么s给出正确的输出而l没有


Tags: inimportweb元素列表forlinkall
2条回答

你每次都在替换列表,它会被覆盖。因此,您将获得迭代之后的最后一个元素!希望有帮助

import urllib2
from bs4 import BeautifulSoup
first=urllib2.urlopen("http://www.admision.unmsm.edu.pe/res20130914/A.html").read()
soup=BeautifulSoup(first)
w=[]
for q in soup.find_all('tr'):
    for link in q.find_all('a'):
        w.append(link["href"])

s = [ i.replace(".","") for i in w ]
print s
l=[]

for t in w:
    l.append(t.replace(".",""))
print l

干杯

在循环中,在每个迭代中替换整个列表,而不是像单行示例中那样附加到列表中

相反,请尝试:

for t in w:
    l.append(t.replace(".",""))

相关问题 更多 >