Reputation: 33
I have the following code for example:
n = ['321','243','780']
b = ['12','56','90']
a = ['178', '765', '111']
E = input('Enter Word...')
qw = 1
Code = ('')
E_ready = [E[no:no+qw] for no in range(0, len(E), qw)]
for code in E_Ready:
letter = random.choice(code)
Code += letter
If you enter the word 'nba' then it will output as 'nba', I want it to output with random elements from each letter's respective list so for example '32112178'
Upvotes: 0
Views: 1750
Reputation: 1426
As Willem van Onsem correctly mentioned in the comments:
"...that is really bad design, call-by-name is rather unsafe. You better use a dictionary."
So, try this:
n = {'option1':'321','option2':'243','option3':'780'}
letter = random.choice(list(n.values()))
Or, shorter, as Chris has mentioned:
d = {'n':[321, 243, 780]}
letter = random.choice(d['n'])
Results from print(letter)
(on both options):
321
321
780
243
etc..
EDIT:
How to add extra variables:
n = 'n'
d = {n:[321, 243, 780]}
letter = random.choice(d[n])
q = 'q'
d[q] = [600, 234, 180]
new_letter = random.choice(d[q])
Now print(new_letter)
gives:
234
180
180
600
etc..
SECOND EDIT (which btw is pure bonus since the question turned into a completely different one then first asked.. therefor, it is left unoptimized. Yet, working nonetheless..):
import random
d = {'n':[321, 243, 780], 'b':['12','56','90'], 'a':['178', '765', '111']}
E = input('Enter Word...')
inputword = list(E)
for key in d.keys():
if key in inputword:
for i in range(len(inputword)):
if inputword[i] == key:
try:
inputword[i] = str(random.choice(d[key]))
except:
pass
result = ''.join(inputword)
print(result)
If input = nba
then output = 32190111
If input = nhhsygbbvvra
then output = 321hhsyg5690vvr178
Etc..
Upvotes: 2
Reputation: 710
I agree with the comment, it is better to use something like:
d = {'n':[mylist]}
letter = random.choice(d['n'])
the problem is that random.choice
works on strings too... it simply considers them to be a list of characters. in your case the code variable and n are supposed to be exactly the same but are in fact not. You could also do
n = [list]
code = n ## only makes any sense, if there
## is a procedure assigns it based on some condition
letter = random.choice(code)
Upvotes: 1
Reputation: 998
Okay, you have a few fundamental issues. When you want to assign one variable to another then you wouldn't put it in quotes. So it should be:
code = n
But actually I'm wondering why you need the variable code at all. You could simply do
import random
code = [ '321', '243', '780' ]
letter = random.choice(code)
print letter
Upvotes: 1