2013-11-25 115 views
0

我試圖刪除「標題」元素從這個名單中,我從網上刮:Unlisting Python列表和刪除元素

x = 
[[(u'title', u'Goals for')], [(u'title', u'Goals against')], [(u'title', u'Penalty goal')], [(u'title', u'Goals for average')], [(u'title', u'Matches Played')], [(u'title', u'Shots on goal')], [(u'title', u'Shots Wide')], [(u'title', u'Free Kicks Received')], [(u'title', u'Offsides')], [(u'title', u'Corner kicks')], [(u'title', u'Wins')], [(u'title', u'Draws')], [(u'title', u'Losses')]] 

我想我最終是

result = ['Goals for', 'Goals against','Penalty goal','Goals for average',....] 

但我可以做 y = x[1][0][1] =>「爲目標的」我不能這樣做x[i][0][1],因爲它是指數我的循環語句中我得到了錯誤

TypeError: list indices must be integers, not tuple

我該如何解決這個問題?

回答

3

我會使用列表理解:

>>> new = [sublist[0][1] for sublist in x] 
>>> pprint.pprint(new) 
[u'Goals for', 
u'Goals against', 
u'Penalty goal', 
u'Goals for average', 
u'Matches Played', 
u'Shots on goal', 
u'Shots Wide', 
u'Free Kicks Received', 
u'Offsides', 
u'Corner kicks', 
u'Wins', 
u'Draws', 
u'Losses'] 

不知道pandas連接是什麼,但。如果您嘗試從MultiIndex中提取一列,則有更簡單的方法。

2

您可以使用列表理解(一般比較常見的,因爲它是清晰,簡潔,並認爲Python化):

x = [[(u'title', u'Goals for')], [(u'title', u'Goals against')], [(u'title', u'Penalty goal')], [(u'title', u'Goals for average')], [(u'title', u'Matches Played')], [(u'title', u'Shots on goal')], [(u'title', u'Shots Wide')], [(u'title', u'Free Kicks Received')], [(u'title', u'Offsides')], [(u'title', u'Corner kicks')], [(u'title', u'Wins')], [(u'title', u'Draws')], [(u'title', u'Losses')]] 
x = [i[0][1:] for i in x] 

或者你可以使用一個for遍歷的x長度:

for i in range(len(x)): 
    x[i] = x[i][0][1:] 

正如原來的答案後指出的,我的另一個原始建議使用Python的del聲明(例如del x[0][0][0])也不會工作,因爲tuple不支持項目刪除。

+0

你listcomp會產生一堆空列表。 :^) – DSM

+0

好,DSM!我沒有注意到第三層嵌套。 ;) – SimonT

1

只是有一個嘗試:

x = [[('title', 'Goals for')], [('title', 'Goals against')], [('title', 'Penalty goal')], [('title', 'Goals for average')], [('title', 'Matches Played')], [('title', 'Shots on goal')], [('title', 'Shots Wide')], [('title', 'Free Kicks Received')], [('title', 'Offsides')], [('title', 'Corner kicks')], [('title', 'Wins')], [('title', 'Draws')], [('title', 'Losses')]] 
print([element[0][1] for element in x ]) 
1

其他解決方案:

>>> map(lambda a: a[0][1], x) 
... [u'Goals for', u'Goals against', u'Penalty goal', u'Goals for average', u'Matches Played', u'Shots on goal', u'Shots Wide', u'Free Kicks Received', u'Offsides', u'Corner kicks', u'Wins', u'Draws', u'Losses'] 
>>>