2009-10-06 58 views
5
thelist = ['a','b','c','d'] 

我怎樣才能在Python中爭奪他們?有誰知道一種方法來打亂列表中的元素?

+2

我想答案可能是'random.shuffle'。 8-) – RichieHindle 2009-10-06 08:00:35

+0

呵呵,你覺得呢? :) – Peter 2009-10-06 08:01:41

+2

完全重複:http://stackoverflow.com/questions/473973/shuffle-an-array-with-python – 2009-10-06 08:07:17

回答

13
>>> import random 
>>> thelist = ['a', 'b', 'c', 'd'] 
>>> random.shuffle(thelist) 
>>> thelist 
['d', 'a', 'c', 'b'] 

您的結果將(希望!)變化。

5

使用來自random模塊shuffle功能:

>>> from random import shuffle 
>>> thelist = ['a','b','c','d'] 
>>> shuffle(thelist) 
>>> thelist 
['c', 'a', 'b', 'd'] 
+9

嘿,你怎麼得到不同的輸出到彼得? ;) – 2009-10-06 08:02:12

+0

在看到眨眼之前,還有誰直接進入了「添加評論」按鈕以獲取最新的內容? :P – 2009-10-06 10:11:45

12
import random 
random.shuffle(thelist) 

注意,這打亂就地列表。

+2

+1表示「就地」。 – 2009-10-06 08:01:33

相關問題