从文本文件Python 3创建3x3网格

时间:2014-08-23 23:33:18

标签: python random grid

我使用的是Python 3,我对此非常陌生。

import random
words = random.sample(open('letters.txt').readlines(), 9)
print(words)  

我找到了解决方案,但它们似乎从未在Python 3中运行。

2 个答案:

答案 0 :(得分:2)

使用rstrip()删除\n换行符:

import random
words = [x.rstrip() for x in random.sample(open('in.txt').readlines(), 9)]

grid = [words[i:i + 3] for i in range(0, len(words), 3)]

[['BLUE', 'ANGRY', 'RED'], ['HAPPY', 'FOO', 'ORANGE'], ['JOYFUL', 'YELLOW', 'SAD']]

如果你想打印出来:

import random

with open('in.txt') as f: # with closes your files automatically 
    words = random.sample([x.rstrip() for x in f],9)
    grid = [words[i:i + 3] for i in range(0, len(words), 3)]
    for x,y,z in grid:
        print (x,y,z)



In [5]: with open('in.txt') as f: # with closes your files automatically 
   ...:             words = random.sample([x.rstrip() for x in f],9)
   ...:             grid = [words[i:i + 3] for i in range(0, len(words), 3)]
   ...:             for x,y,z in grid:
   ...:                     print (x,y,z)
   ...:         
BLUE GREEN SAD
RED JOYFUL FOO
ORANGE HAPPY YELLOW

答案 1 :(得分:0)

在stackoverflow中进行了一些搜索后,我找到了这个 Print new output on same line

所以也许可以做类似的事情(这段代码没有经过测试):

import random
// We store all the words to keep reference to the one is not displayed
dictionary = open('words.txt').readlines() 

words = random.sample(dictionary, 9)
for index in range(9)
  ending = ' '
  if index+1 % 3 == 0
    ending = '\n'
  print(words[i], end=ending)