from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
Am trying to make a basic memory game on python. Above is my current code to generate random numbers in a list but I want it to print out a string instead of an integer e.g. 'duck' instead of #5 every time it is printed. When I input something like:
print(x[4])
Any help would be appreciated
One way is to put all of your options in a list and then use random.suffle() to shuffle the contents in-place. If you don't want to modify your original list, be sure to make a copy first.
items = ['duck', 'goose', 'swan']
random.shuffle(items)
# ['goose', 'duck', 'swan']
If you really need to keep track of where they came from (i.e. their original index), you can use a tuple to hold your items and their original index and then shuffle that.
tupled_items = [x for x in enumerate(items)]
random.shuffle(tupled_items)
# [(1, 'goose'), (0, 'duck'), (2, 'swan')]
you can use some package to generate random words for example https://pypi.python.org/pypi/RandomWords/0.1.5 and then do something like
from random_words import RandomWords
rw = RandomWords()
x = [rw.random_word() for _ in range(10)]
print x
If you already know words you want to use, make it as a dict, and do something like this Randomly shuffling a dictionary in Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With