繁体   English   中英

取消列出python列表并删除元素

[英]Unlisting a python list and removing element

我正在尝试从网络上删除的此列表中删除“ title”元素:

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] =>'Goals for'我不能做x[i][0][1]因为它是我的for循环语句中的索引,我得到了错误

TypeError:列表索引必须是整数,而不是元组

我该如何解决?

我会使用列表理解:

>>> 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提取列,则有更简单的方法。

您可以使用列表理解(通常更常见,因为它清晰,简洁并且被认为是Pythonic):

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]

或者,您可以在x的长度上使用for循环:

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

正如原始答案之后所指出的那样,我其他使用Python的del语句的原始建议(例如del x[0][0][0] )也不会起作用,因为tuple不支持项目删除。

尝试一下:

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 ])

其他解决方案:

>>> 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']
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM