2011-05-29 89 views
6

是否有pythonic的方式來切片序列類型,使得返回的切片是隨機長度隨機順序?例如,像:Python隨機切片成語

>>> l=["a","b","c","d","e"] 
>>> rs=l[*:*] 
>>> rs 
['e','c'] 

回答

13

......怎麼

random.sample(l, random.randint(1, len(l))) 

以文檔爲隨機模塊快速鏈接可以發現here

4

沒有我知道的成語,但random.sample做你所需要的。

>>> from random import sample, randint 
>>> 
>>> def random_sample(seq): 
...  return sample(seq, randint(0, len(seq))) 
... 
>>> a = range(0,10) 
>>> random_sample(a) 
[] 
>>> random_sample(a) 
[4, 3, 9, 6, 7, 1, 0] 
>>> random_sample(a) 
[2, 8, 0, 4, 3, 6, 9, 1, 5, 7] 
+2

爲什麼選擇投票? – 2011-05-29 17:07:10

4

有一個微妙的區別,既不是你的問題也不是其他答案的地址,所以我覺得我應該指出。下面的例子說明了這一點。

>>> random.sample(range(10), 5) 
[9, 2, 3, 6, 4] 
>>> random.sample(range(10)[:5], 5) 
[1, 2, 3, 4, 0] 

正如你可以從輸出中看到,第一個版本沒有「切片」列表中,但只有樣品,所以返回值可以從列表中的任何地方。如果你硬是要一個列表的「切片」 - 也就是說,如果你想約束抽樣前樣本空間 - 那麼下面沒有做你想要什麼:

random.sample(l, random.randint(1, len(l))) 

相反,你會必須做這樣的事情:

sample_len = random.randint(1, len(l)) 
random.sample(l[:sample_len], sample_len) 

但我認爲一個更好的方式來做到這將是像這樣:

shuffled = l[:random.randint(1, len(l))] 
random.shuffle(shuffled) 

不幸的是還有的shuffle沒有複製回版本,我知道(即一個shuffled類似於sorted)。

+0

+1,以瞭解文字「切片」評論和目的解決方案。 – 2011-05-29 18:10:41

+0

@senderle''shuffled = lambda p:sample(p,len(p))''' – 2017-04-28 04:09:50