Python:如果子列表中的字符串以" - / 2 ......."开头,则删除列表中的子列表

时间:2017-03-08 17:07:25

标签: python list tuples python-3.5

我有我的

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

我试过了,

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

但结果如(' - / 229613_at',12),(' - / 232203_at',11),(' - / 244174_at',6 ),(' - / 237146_at',6)仍然出现。

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)

你并不遥远。 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)]
相关问题