-1

I have 4 lists and want to choose a random list and then choose a random item of it. this is my code but it doesn't work properly. can you help please?

import random
w=['*', '&' ,'^', '%' ,'$' ,'#', '@' ,'!']
w1=['w','a','s','r','i','t','e','n','d','c']
w2=['W','A','S','R','I','T','E','N','D','C',]
w3=['1','2']

p=''
j=8
while j:
   e=random.choice(['w','w1','w2','w3'])
   q=random.choice(f'{f"{e}"}')
   p+=q
   j-=1

print(p)

and this is the wrong output that doesnt select from the lists:

w3www3ww
Beryl Amend
  • 131
  • 1
  • 9

2 Answers2

1

You can use list comprehension and nest the random.choice calls like so:

import random

w = ['*', '&', '^', '%', '$', '#', '@', '!']
w1 = ['w', 'a', 's', 'r', 'i', 't', 'e', 'n', 'd', 'c']
w2 = ['W', 'A', 'S', 'R', 'I', 'T', 'E', 'N', 'D', 'C']
w3 = ['1', '2']

wlist = [w, w1, w2, w3]

p = ''.join(random.choice(random.choice(wlist)) for _ in range(8))

print(p)

Using list unpacking, you can shorten the code even more:

wlist = [*w, *w1, *w2, *w3]

p = ''.join(random.choice(wlist) for _ in range(8))

Make sure your list contains the variables, not strings.

B Remmelzwaal
  • 1,581
  • 2
  • 4
  • 11
1
import random

w = ['*', '&', '^', '%', '$', '#', '@', '!']
w1 = ['w', 'a', 's', 'r', 'i', 't', 'e', 'n', 'd', 'c']
w2 = ['W', 'A', 'S', 'R', 'I', 'T', 'E', 'N', 'D', 'C']
w3 = ['1', '2']

p = ''
j = 8
while j:
    e = random.choice([w, w1, w2, w3])  # Choose between the lists w, w1, w2, w3
    q = random.choice(e)  # Choose a random character from the chosen list
    p += q
    j -= 1

print(p)