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
>Solution :
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.