【发布时间】:2016-09-10 20:57:34
【问题描述】:
我正在做某事。这是代码需要做的事情
- 读取文件
- 将每一行放入数组中的一个项目中
- 将数组随机排列成尽可能多的随机排列。下面会解释
- 创建一个新文件来存储打乱的单词
3 号解释: file.txt 包含以下内容
this
is
a
test
它需要洗牌到任何可能的结果。像这样
this is a test
this a is test
this test is a
this test a is
等等等等。有 16 种可能的结果,所以我不会用它来回答我的问题。
我在 Python 2.7 中使用以下代码
file = raw_input('Enter File Name: ')
with open(file, 'r+') as f:
array = list(f)
print array
输出是这样的,完全没问题('\n'除外):
['this\n', 'is\n', 'a\n', 'test']
现在,每当我使用 shuffle() 时,我都会使用这段代码
from random import shuffle
file = raw_input('Enter File Name: ')
with open(file, 'r+') as f:
array = list(f)
new = shuffle(array)
print new
输出是这样的:
None
我知道为了写,我需要使用 w+ 并执行 f.write(new) 然后 f.close(),它会清除我的 file.txt 并将其保存为空白
我该怎么做?
【问题讨论】:
-
不会有 4 个吧! = 24 种可能性而不是 16 种?无论如何——你熟悉
itertools吗? -
哦,是的。你是对的,我做了 4*4 而不是阶乘。反正我不是。我去看看!
标签: arrays python-2.7 file