I have a list of 6 words from a text file and would like to open the file to read the list of words as a 3x2 grid, also being able to randomise the order of the words every time the program is run.
words are:
cat, dog, hamster, frog, snail, snake
i want them to display as: (but every time the program is run to do this in a random order)
cat dog hamster
frog snail snake
so far all i've managed to do is get a single word from the list of 6 words to appear in a random order using - help would be much appriciated
import random
words_file = random.choice(open('words.txt', 'r').readlines())
print words_file
Here's another one:
First we read the contents of the file and pick six random lines (make sure your lines only contain a single word). Then we group the words into lists of threes and print them using string formatting. The
<10
in the format brackets left-aligns the text and pads each item with 10 spaces.You'll want to look into string formatting!
There are better ways to run through your list grouping by threes, but this works for your limited test case. Here's a link to some more information on chunking lists
My favorite recipe is chunking with
zip
anditer
:For selecting the 6 words, you should try
random.sample
: