Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python remove one worded strings from list

Tags:

python

words = [['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]

I have a list of lists containing strings. I understand how to remove specific elements from a list, but not how to remove those that are only one word. My desired output would be:

final = [['hey you'], ['ok no', 'hey ma']]

What I'm trying but I think it's totally wrong....

remove = [' ']
check_list = []

for i in words:
    tmp = []
    for v in i:
        a = v.split()
        j = ' '.join([i for i in a if i not in remove])
        tmp.append(j)

    check_list.append(tmp)
print check_list
like image 274
user47467 Avatar asked Jan 25 '26 18:01

user47467


2 Answers

You can do:

words = [['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]
final = [[x for x in sub if ' ' in x.strip()] for sub in words]
# [['hey you'], ['ok no', 'hey ma']]

where I simply search for spaces in all strings.

like image 192
Julien Spronck Avatar answered Jan 28 '26 08:01

Julien Spronck


You can use filter:

for words in list_of_lists: 
    words[:] = list(filter(lambda x: ' ' in x.strip(), words))

Or list comprehension:

for words in list_of_lists:
    words[:] = [x for x in words if ' ' in x.strip()]
like image 21
AndreyT Avatar answered Jan 28 '26 08:01

AndreyT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!