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
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.
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With