0

So I have a list of lists where each element corresponds to words for a particular document e.g the format is:

[['alice','wonderland',......],['cat','hat',....],......]

I have a small list of words that are contained within this list of lists and I want to reverse these words in that list of lists with a 50% chance (e.g if 'alice' is in my list, around 50% of occurances of 'alice' in the list of lists will become 'ecila'.

Here is my code so far:

words = ['alice','wonderland','cat','hat',....]
sublist = ['alice','cat','hat']

import random
output = [w[::-1] if w in sublist and random.choice([True, False]) else w
       for w in words]

I can only seem to get it working for when words is a list but not for when it is a list of lists, could anyone help?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
IVB_CODING
  • 23
  • 5

1 Answers1

2

As it is mentioned in the comments you should use nested loops. Here is a code with nested loop to achieve what you are after:

words = [['alice','wonderland'],['cat','hat']]

sublist = ['alice','cat','hat']

import random
output = [[w[::-1] if w in sublist and random.choice([True, False])  else w
      for w in wordsList ]for wordsList in words]
output

and here is the colab to test it: https://colab.research.google.com/drive/1uEyM8CPDg_eMhpQl9385CGabnAL2OLn-?usp=sharing