将子列表添加到自己的列表中

时间:2018-02-23 17:14:57

标签: python python-3.x list beautifulsoup sublist

我正在尝试创建一个程序,该程序从各个网站获取nba团队数据,并以列表形式为每个团队编制统计数据。

IE:亚特兰大= [' 107.5',' 105.6',' .516',' .543']

数字意味着每场比赛得分,对手每场比赛得分,RPI和篮板率。

我现在遇到了一个错误,只是试图找出如何获取用户输入,在列表列表中查找该团队的列表,以及从该列表中提取某个索引。

import urllib.request
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib.request.urlopen("http://www.espn.com/nba/stats/rpi"), "lxml")
data = [[x.text for x in row.find_all("td")] for row in soup.select("table tr")]
tables = []
team_s = []
for row in data:
   tables.append(row)
team_s = [item[0] for item in tables]
team_s = [el.replace('\xa0',' ') for el in team_s]   
print (team_s[2])

print ("-" * 80)
print ("Welcome to the NBA betting helper. \nTo start, enter the city of the home team for team 1. Then enter the city of the away team for team 2.")
print ("-" * 80)
home = input("Enter the city of team 1 (Home Team):")
away = input("Enter the city of team 2 (Away Team):")

Atlanta = []
Boston = []


try:
   print (team_s.index("Detroit"))
except ValueError:
   print ("word1 not in list.")

def hometeam():
    print ("ex")        

def awayteam():
    print ("ex")     

#Main

hometeam()
awayteam()

1 个答案:

答案 0 :(得分:0)

您可以创建一个包含每个团队字典的列表,其中键作为团队名称,值作为统计信息列表(RPI,PF,PA)。

kubelet-client.key
kubelet.crt
kubelet.key

部分输出:

>>> soup = BeautifulSoup(urllib.request.urlopen("http://www.espn.com/nba/stats/rpi"), "lxml")
>>> data = [[x.text for x in row.find_all("td")] for row in soup.select("table tr")[2:]]
>>> stats = {team[1]: [team[2], team[8], team[9]] for team in data}
>>> print(stats)

请注意,我已将{'Golden State': ['.571', '6853', '6376'], 'Houston': ['.562', '6504', '6007'], 'Toronto': ['.553', '6376', '5892'], 'Boston': ['.543', '6085', '5878'], ...} 列表与soup.select(...)分开,因为前2个列表不包含团队统计信息。

其中,字典的格式为[2:]。我没有增加反弹百分比,因为我无法在表格中找到它。但我确定你可以添加看上面的代码。

现在,您可以从用户那里获取输入并打印相应的统计信息,如下所示:

{'team_name': [RPI, PF, PA]}