2012-03-19 55 views
2

之前,我問我的問題,讓我得到這個直...爭奪Python列表

這不是Does anyone know a way to scramble the elements in a list?Shuffle an array with python, randomize array item order with python重複。我會解釋爲什麼......

我想知道如何爭奪一個數組,作出新的副本。由於random.shuffle()修改了列表(並返回None),我想知道是否有另一種方法來執行此操作,因此我可以執行scrambled=scramblearray()。如果沒有內置函數,我可以定義一個函數來做到這一點,如果可能的話。

+4

出了什麼問題做一個新的副本,然後爭先恐後呢? – Marcin 2012-03-19 13:02:14

+1

可能的重複[亂數組與python](http://stackoverflow.com/questions/473973/shuffle-an-array-with-python) – Marcin 2012-03-19 13:04:16

+0

@Marcin個人而言,我不認爲這些答案可以合併與[隨機播放數組與Python]答案(http://stackoverflow.com/questions/473973/shuffle-an-array-with-python) – CoffeeRain 2012-03-19 13:17:26

回答

13
def scrambled(orig): 
    dest = orig[:] 
    random.shuffle(dest) 
    return dest 

及用量:

import random 
a = range(10) 
b = scrambled(a) 
print a, b 

輸出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [6, 0, 2, 3, 1, 7, 8, 5, 4, 9] 
3

複製陣列然後擾頻它:

import random 

array = range(10) 
newarr = array[:] # shallow copy should be fine for this 
random.shuffle(newarr) 
#return newarr if needs be. 
zip(array, newarr) # just to show they're different 

Out[163]: 
[(0, 4), 
(1, 8), 
(2, 2), 
(3, 5), 
(4, 1), 
(5, 6), 
(6, 0), 
(7, 3), 
(8, 7), 
(9, 9)] 
4

使用排序()。它返回一個新的列表,如果你使用一個隨機數作爲密鑰,它將被加密。

import random 
a = range(10) 
b = sorted(a, key = lambda x: random.random()) 
print a, b 

輸出

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [5, 9, 0, 8, 7, 2, 6, 4, 1, 3]