我正在處理某些事情。下面是該代碼需要做如何讀取文件,將內容放在數組中,將數組隨機混合,然後將混排數組寫入Python中的文件2.7
- 閱讀將每行成一個項目在一個陣列
- 文件
- 陣列洗牌成它可以作爲許多可能的洗牌。下面
- 將解釋創建一個新的文件來存儲洗牌的話
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(新),然後f.close(),它會清除我的file.txt的,並將其保存空白
我該如何去做這件事?
難道會有4! = 24種可能性而不是16種?無論如何 - 你是否熟悉'itertools'? –
哦,是的。你是對的,我做了4 * 4而不是階乘。無論如何,我不是。我會看一看! – notissac