Reputation: 1093
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
Upvotes: 3
Views: 121
Reputation: 1499
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()]
Upvotes: 2
Reputation: 348
Here is the logic for each list, this you can loop and use
wordlist=['hey', 'hey you']
filter(None, [ p if re.sub('\\b\\w+\\b', '', p) != '' else None for p in wordlist ])
output
['hey you']
Upvotes: -1
Reputation: 3405
Functional programming way to do that:
>>> words
[['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]
>>> map(lambda v: ' '.join(v),
filter(lambda y: len(y) > 1, map(lambda x: x.split(), words[1])))
['ok no', 'hey ma']
>>> map(lambda z: map(lambda v: ' '.join(v),
filter(lambda y: len(y) > 1, map(lambda x: x.split(), z))), words)
[['hey you'], ['ok no', 'hey ma']]
Upvotes: 0
Reputation: 15423
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.
Upvotes: 5