Reputation: 117
I am making a hangman game and I want to be able to replace the list of original words with a list of new words typed in by the user. At the minute my code is this:
gamewords[:] = newgamewords[:]
But this does not seem to work...
The original list is this:
gamewords= ['blue','violet','red','orange','fuchsia','cyan','magenta','azure','black','turquoise','pink','scarlet']
A word is then chosen for the list randomly
word=gamewords[random.randint(0,len(gamewords)-1)]
i want to change it so that the word is chosen from the new list, how do i do this?
Upvotes: 8
Views: 35010
Reputation: 5395
The obvious choice of functions to use to select one, or a set number of items randomly from a larger list would be random.choice()
or random.choices()
.
>>> gamewords= ['blue','violet','red','orange','fuchsia','cyan','magenta','azure','black','turquoise','pink','scarlet']
>>> random.choice(gamewords)
'turquoise'
>>> random.choice(gamewords)
'orange'
>>> random.choice(gamewords)
'cyan'
>>> random.choices(gamewords, k=3)
['fuchsia', 'orange', 'red']
>>> random.choices(gamewords, k=2)
['turquoise', 'black']
>>>
Upvotes: 1
Reputation: 289
Not sure if you were able to find the answer to this but I had a similar issue and I resolved it using this method:
for x, y in zip(original_col, np.arange(0, len(original_col), 1)):
df['Term Ldesc'] = df['Term Ldesc'].replace(x, y)
Hope this helps!
Upvotes: 0
Reputation: 129507
You probably meant to do this:
gamewords = newgamewords[:] # i.e. copy newgamewords
Another alternative would be
gamewords = list(newgamewords)
I find the latter more readable.
Note that when you 'copy' a list like both of these approaches do, changes to the new copied list will not effect the original. If you simply assigned newgamewords
to gamewords
(i.e. gamewords = newgamewords
), then changes to gamewords
would effect newgamewords
.
Relevant Documentation
Upvotes: 3
Reputation: 616
I'm not sure what you exactly want. There are two options:
gamewords = newgamewords[:]
gamewords = newgamewords
The difference is that the first option copies the elements of newgamewords and assigns it to gamewords. The second option just assigns a reference of newgamewords to gamewords. Using the second version, you would change the original newgamewords-list if you changed gamewords.
Because you didn't give more of your source code I can't decide which will work properly for you, you have to figure it out yourself.
Upvotes: 1