3
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
6
  • "I think it's totally wrong" - does it work? Have you tested it? Commented Feb 18, 2016 at 14:10
  • yes, ive tested it, but check_list outputs the same as words Commented Feb 18, 2016 at 14:11
  • 1
    Alright, so give a minimal reproducible example. Commented Feb 18, 2016 at 14:11
  • Im not sure I understand what you mean... Commented Feb 18, 2016 at 14:13
  • Then read the link. Cut your code down and give example input with expected and actual output, so others don't have to comb through it. Commented Feb 18, 2016 at 14:14

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@PeterWood ... just corrected that by stripping the strings first
2

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()]

Comments

0

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']]

Comments

-1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.