我试图使用下面的代码拆分包含我需要的数据的高度嵌套的列表集:
url = 'http://www.whoscored.com/stagestatfeed/9155/stageteams/'
url = str(''.join(url[0:3]))
params = {
'against': '0',
'field': '0',
'teamId': '-1',
'type': '8'
}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'Host': 'www.whoscored.com',
'Referer': 'http://www.whoscored.com/'}
responser = requests.get(url, params=params, headers=headers)
responser = json.loads(responser.text.replace("'", '"').decode('cp1252'))
results = defaultdict(int)
for match in responser:
for num_events, team, events in match:
print "w = ", num_events
print "x = ", team
for y in events:
print "y = ", events
此示例输出如下:
w = 13
x = Arsenal
y = [[[[u'goal', u'openplay', u'header', [1]], [u'goal', u'openplay', u'leftfoot', [1]],
[u'goal', u'openplay', u'rightfoot', [3]], [u'goal', u'owngoal', u'rightfoot', [1]], [u'miss',
u'corner', u'header', [2]], [u'miss', u'corner', u'leftfoot', [3]], [u'miss', u'corner',
u'rightfoot', [2]], [u'miss', u'crossedfreekick', u'rightfoot', [2]], [u'miss',
u'directfreekick',
u'leftfoot', [1]], [u'miss', u'openplay', u'header', [2]], [u'miss', u'openplay',
u'leftfoot', [16]], [u'miss', u'openplay', u'rightfoot', [23]]]]]
...
...
...
w = 171
x = Queens Park Rangers
y = [[[[u'goal', u'openplay', u'leftfoot', [1]], [u'miss', u'corner', u'header', [5]], [u'miss',
u'crossedfreekick', u'header', [1]], [u'miss', u'directfreekick', u'rightfoot', [2]],
[u'miss', u'openplay', u'header', [1]], [u'miss', u'openplay', u'leftfoot', [4]], [u'miss',
u'openplay', u'rightfoot', [23]], [u'miss', u'throwin', u'header', [1]]]]]
我想要的是每个团队的输出结果如下:
w = 13
x = Arsenal
y = [u'goal', u'openplay', u'header', [1]]
y = [u'goal', u'openplay', u'leftfoot', [1]]
y = [u'goal', u'openplay', u'rightfoot', [3]]
...
...
...
y = [u'miss', u'openplay', u'rightfoot', [23]]
在这个例子中,我在代码中迭代每个包含变量y
的嵌套列表,并依次打印每个。我已经为for循环和列表推导尝试了各种旋转,但是没有能够获得有效的东西。
有人可以提出答案吗?
由于
答案 0 :(得分:1)
只需使用索引和子列表上的迭代访问:
for y in events[0]:
for sub in y:
print ("y = ", sub)
w = 162
x = Crystal Palace
y = [u'goal', u'corner', u'rightfoot', [1]]
y = [u'goal', u'crossedfreekick', u'header', [1]]
y = [u'goal', u'openplay', u'rightfoot', [1]]
y = [u'miss', u'corner', u'header', [6]]
y = [u'miss', u'corner', u'rightfoot', [1]]
y = [u'miss', u'crossedfreekick', u'header', [2]]
y = [u'miss', u'crossedfreekick', u'leftfoot', [1]]
y = [u'miss', u'crossedfreekick', u'rightfoot', [3]]
y = [u'miss', u'openplay', u'header', [2]]
y = [u'miss', u'openplay', u'leftfoot', [9]]
y = [u'miss', u'openplay', u'rightfoot', [14]]
w = 175
x = West Bromwich Albion
y = [u'goal', u'corner', u'header', [2]]
y = [u'goal', u'openplay', u'rightfoot', [3]]
y = [u'goal', u'penalty', u'rightfoot', [1]]
y = [u'miss', u'corner', u'header', [1]]
y = [u'miss', u'directfreekick', u'rightfoot', [3]]
y = [u'miss', u'openplay', u'leftfoot', [12]]
y = [u'miss', u'openplay', u'rightfoot', [21]]