Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing a repetitive item in a list, ignores other items

i have a list of words in Polish and i want to remove the single words in this list. that means i only want sentences. that’s why i have a an If with this condition if len(item.split())<=1: . the Problem occourse when i run the function. it removes only this word: Powrót and ignores the words that come after it like Energetyka.

_webTextList=['MOTORYZACJA', 'Szukaj w serwisie', 'Powrót', 'Energetyka', 'Powrót', 'Gazownictwo', 'Powrót', 'Górnictwo', 'Powrót', 'Hutnictwo', 'Powrót', 'Nafta', 'Powrót', 'Chemia', ...]#the list of words and sentenses.

def remove_one_words_from_list(_webTextList):
 for item in _webTextList:
   if len(item.split())<=1:
     _webTextList.remove(item)
 return _webTextList   

i can not figure out what i’m doing wrong. tnx for the help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a list comprehension and keep the strings that contain a space:

_webTextList = ['MOTORYZACJA', 'Szukaj w serwisie', 'Powrót', 'Energetyka', 'Powrót', 'Gazownictwo', 'Powrót', 'Górnictwo', 'Powrót', 'Hutnictwo', 'Powrót', 'Nafta', 'Powrót', 'Chemia']

_webTextList = [s for s in _webTextList if ' ' in s]

NB. if you really want to use the length of split’s output as condition: [s for s in _webTextList if len(item.split())>1].

Output: ['Szukaj w serwisie']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading