Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a string print out on list instead of integer

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

like image 770
Edward White Avatar asked Dec 07 '25 08:12

Edward White


2 Answers

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')]
like image 196
Suever Avatar answered Dec 09 '25 23:12

Suever


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

like image 41
Ostap Khl Avatar answered Dec 09 '25 21:12

Ostap Khl