Skip to main content
 首页 » 编程设计

Python 合并列表

2025年05月04日32落叶

我想从 website 中得到数字的总和.我这样做:

lst = list() 
url = raw_input('Enter - ') 
html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 
tags = soup('span') 
for tag in tags: 
    lst.append(map(int,tag.contents)) 
print lst 

但如果我没记错的话,我现在每个数字都有一个子列表。因此,sum(lst) 不起作用。我怎样才能合并子列表或将数字放在一个列表中开始?谢谢!

请您参考如下方法:

您可以使用以下内容:

import urllib 
from bs4 import BeautifulSoup 
 
url = 'http://python-data.dr-chuck.net/comments_213060.html' 
html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 
tags = soup('span') 
lst = [int(tag.text) for tag in tags] 
print(sum(lst)) 

输出

2838