rozjni
rozjni

Reputation: 49

Python: list/array, remove doubled words string

I want to filter only elements that have only one word and make a new array of it. How could I do this in Python?

Array:

['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']

NewArray should be:

['somewhat', 'all', 'dictator', 'was', 'in']

Upvotes: 0

Views: 62

Answers (3)

Sujan Adiga
Sujan Adiga

Reputation: 1371

Using re.match and filter

import re


MATCH_SINGLE_WORD = re.compile(r"^\w+$")

inp = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
out = filter(MATCH_SINGLE_WORD.match, inp)

print(list(out)) # If you need to print. Otherwise, out is a generator that can be traversed(once) later

This solution would handle \n or \t being present in word boundaries as well along with single whitespace character.

If you want to handle leading and trailing whitespaces,

import re
from operator import methodcaller

MATCH_SINGLE_WORD = re.compile(r"^\w+$")

inp = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
out = filter(MATCH_SINGLE_WORD.match, map(methodcaller("strip"), inp))

Upvotes: 0

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

filter the list with a list comprehension

old_list = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']


new_list = [x for x in old_list if len(x.split()) == 1]

Returns:

['somewhat', 'all', 'dictator', 'was', 'in']

Upvotes: 2

Chandella07
Chandella07

Reputation: 2117

try this

a= ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']

print([i for i in a if " " not in i])

Output:

['somewhat', 'all', 'dictator', 'was', 'in']

Upvotes: 3

Related Questions