Python合并列表

Python合并列表,python,beautifulsoup,Python,Beautifulsoup,我想从a中得到数字的和。我这样做: 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)不起作用。如何

我想从a中得到数字的和。我这样做:

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)
不起作用。如何合并子列表或将数字放在一个列表中开始?谢谢

您只需使用:

请注意,这里使用的是返回元素的“文本”,而不是元素子元素的文本列表

请注意,我还改进了定位器,并检查了
span
s以获得
comments
类。

您可以使用:

请注意,这里使用的是返回元素的“文本”,而不是元素子元素的文本列表


请注意,我还改进了定位器,并检查了
span
s以获得
comments
类。

您可以使用以下内容:

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

您可以使用以下选项:

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

那么,当您打印
lst
时,您得到了什么?您试过了吗?是的,lst,很抱歉造成混淆。或者更准确地说,sum(lst)和for sum(lst)我得到了:TypeError:不支持+:“int”和“list”的操作数类型。那么,当您打印
lst
时,您得到了什么?您尝试过了吗?是的,lst,很抱歉造成混淆。或者更确切地说,sum(lst)和sum(lst)我得到了:TypeError:不支持的+操作数类型:'int'和'list'谢谢,这太棒了!你能告诉我为什么需要
[0]
吗?仔细想想,实际上最好使用
tag.text
而不是
tag.contents[0]
。请参阅上面更新的答案。谢谢,这太棒了!你能告诉我为什么需要
[0]
吗?仔细想想,实际上最好使用
tag.text
而不是
tag.contents[0]
。见上面更新的答案。