【问题标题】:Adding sublists to their own list将子列表添加到自己的列表中
【发布时间】:2018-02-23 17:14:56
【问题描述】:

我正在尝试创建一个程序,该程序从各个网站获取 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()

【问题讨论】:

  • 我在表格中看不到反弹百分比列。你这是什么意思?
  • "I'm running into an error right now",那个错误是……?
  • 对不起,我也在使用这个链接:espn.com/nba/statistics/team/_/stat/team-comparison-per-game 但错误是当我去索引子列表时,我发现它超出了范围。不过我现在已经准备好了。

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


【解决方案1】:

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

>>> 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:] 分开,因为前两个列表不包含球队的统计数据。

其中,字典的格式为{'team_name': [RPI, PF, PA]}。我没有添加反弹百分比,因为我在表中找不到它。但是我相信您可以通过查看上面的代码来添加。

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

>>> home = input("Enter the city of team 1 (Home Team): ")
Enter the city of team 1 (Home Team): Boston
>>> print(stats[home])
['.543', '6085', '5878']

【讨论】:

  • @JackHudgins,请注意data = ... 行中的更改,我已将其从列表更改为字典。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2017-02-20
  • 2011-05-31
相关资源
最近更新 更多