Python:如果子列表中的字符串以“/2…”开头,则删除列表中的子列表

2024-10-06 07:39:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有我的

datacount= ([('mark / 222696_at', 19), ('jason / 210393_at', 15), ('mickey / 213880_at', 15), ('mo / 228649_at', 13), ('nick / 229481_at', 12), ('nikoo / 1553115_at', 12), ('- / 229613_at', 12)]

但是我想删除列表中的元组,它以“-/2”开头,比如('-/229613_at',12)。在

我试过了

^{pr2}$

但是,诸如('-/229613'u at',12),('-/232203'u at',11)、('-/244174_at',6)、('-/237146_at',6)的结果仍然存在。在


Tags: 列表nickatmo元组markjasonpr2
2条回答

试试这个:

datacount = [x for x in datacount if not x[0].startswith('- / 2')]

不完全确定您用x[0] not in ['str.startwith(- / 2) == True']尝试了什么,但它看起来像是其他语言中可能出现的某种模式。在Python中,这实际上检查x[0]是否等于字符串'str.startwith(- / 2) == True'。在

你离得不远了。在in检查中,你似乎对所发生的事情有一个错误的心理模型。在

我建议以下列表理解,以解包元组以获得更好的易读性为特点(而不是x[0]索引):

>>> [(string, count) for string, count in datacount if not string.startswith('- / 2')]
[('mark / 222696_at', 19), ('jason / 210393_at', 15), ('mickey / 213880_at', 15), ('mo / 228649_at', 13), ('nick / 229481_at', 12), ('nikoo / 1553115_at', 12)]

相关问题 更多 >