简体   繁体   中英

How do replace a list with another list in python?

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?

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 (ie gamewords = newgamewords ), then changes to gamewords would effect newgamewords .


Relevant Documentation

I'm not sure what you exactly want. There are two options:

  1. gamewords = newgamewords[:]
  2. 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.

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']
>>> 

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM