0
import random
p = ['hello','hey','hi'],['brother','bro','sir'],['me','myself'],['a'],['hero']
print(random.choices(random.choices(p)))

Desired output : hello bro myself a hero

2 Answers2

2

Use random.choicenot random.choices

import random
p = ['hello','hey','hi'],['brother','bro','sir'],['me','myself'],['a'],['hero']
selection = [random.choice(x) for x in p]
output = ' '.join(selection)
print(output)
# "hello bro myself a hero" (or something else, it's random)
Jan Christoph Terasa
  • 5,781
  • 24
  • 34
  • @cs95 I intentionally chose `selection` to be a generator, not a list comprehension. – Jan Christoph Terasa Dec 20 '19 at 07:49
  • 1
    [It's a little faster to pass `str.join` a list.](https://stackoverflow.com/a/9061024/4909087) – cs95 Dec 20 '19 at 07:51
  • @cs95 Please re-add your answer, instead of modifying mine to look like yours. Also, I usually pass the generator expression to `join` directly, but I also intentionally made the code more verbose so the OP can more easily understand the steps. – Jan Christoph Terasa Dec 20 '19 at 07:51
  • I didn't want to because you beat me to the punch and a difference of braces isn't enough of a reason for a separate answer. – cs95 Dec 20 '19 at 07:52
  • @cs95 OK, fair enough. Thank you for the hint about the performance. – Jan Christoph Terasa Dec 20 '19 at 07:53
2

You can try this:

import itertools
import random
' '.join(list(itertools.chain(*list(map(random.choices, p))))) 

# 'hey bro me a hero'
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24