Home > Software engineering >  Pick a random word from a list of list of words, but skip empty string
Pick a random word from a list of list of words, but skip empty string

Time:08-04

Context

An empty list:

my_list = []

I also have a list of lists of strings:

words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]

But note that there are some elements in the lists that are null.

Ideal output

I want to randomly choose a non null element from each list in words_list and append that to my_list as an element.

e.g.

>> my_list 
['this', 'list', 'of']

What I currently have

for i in words_list:
    my_list.append(random.choice(words))

My issue

but it throws this error:

  File "random_word_match.py", line 56, in <module>
    get_random_word(lines)
  File "random_word_match.py", line 51, in get_random_word
    word_list.append(random.choice(words))
  File "/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py", line 261, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

What I don't want

I don't want to only append the first non null element I don't want null values in my_list

CodePudding user response:

Maybe you can try to start thinking this way:

The idea is quite simple - just go through the list of words, and choose the non-empty word then passing to choice.

>>> for word in words_list:
    wd = choice([w for w in word if w])   # if w is non-null, choice will pick it...
    print(wd)

# then just add those non-null word into your my_list --- leave as exercise.
# Like this: 
>>> for word in words_list:
    wd = choice([w for w in word if w])
    my_list.append(wd)    
  
>>> my_list
['this', 'a', 'lists']

# Later, you could even simplify this into a List Comprehension. 

CodePudding user response:

You can use list comprehension:

from random import choice

words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]

output = [choice([word for word in words if word]) for words in words_list]

print(output) # ['is', 'a', 'lists']

CodePudding user response:

Try below code and see if it works for you:

import random
my_list = []
words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]
for sublist in words_list:
    filtered_list = list(filter(None, sublist))
    my_list.append(random.choice(filtered_list))
print(my_list)
  • Related