2017-03-08 30 views
1

我有我的的Python:如果内部子列表中的字符串开头的列表中删除子列表“ -/2 ......”

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)仍然显示。

+0

''str.startwith( -/2)== True''是一个字符串,不是python表达式... –

+0

'datacount'是元组还是列表?因为它起始为一个元组,并以列表结尾... –

+0

我用这个,它工作 datacount = [x for datacount if not x [0] .startswith(“ - /”)] 对不起,它的列表,里面有元组。 –

回答

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

你并不遥远。 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)] 
+0

谢谢大家,我是python的新手,它比excel中的手动工作快得多。 –

相关问题