Removing an item from list matching a substring

怎甘沉沦 提交于 2019-11-30 01:49:23

How about something simple like:

>>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
['this doesnt', 'this shouldnt', 'this isnt', 'this musnt']

This should work:

[i for i in sents if not ('@$\t' in i or '#' in i)]

If you want only things that begin with those specified sentential use the str.startswith(stringOfInterest) method

Another technique using filter

filter( lambda s: not (s[0:3]=="@$\t" or s[0]=="#"), sents)

The problem with your orignal approach is when you're on list item i and determine it should be deleted, you remove it from the list, which slides the i+1 item into the i position. The next iteration of the loop you're at index i+1 but the item is actually i+2.

Make sense?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!