Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python随机切片习语_Python_Random_Slice - Fatal编程技术网

Python随机切片习语

Python随机切片习语,python,random,slice,Python,Random,Slice,是否有一种pythonic方法对序列类型进行切片,以使返回的切片具有随机长度和随机顺序?例如,类似于: >>> l=["a","b","c","d","e"] >>> rs=l[*:*] >>> rs ['e','c'] 那么 random.sample(l, random.randint(1, len(l))) 可以找到随机模块文档的快速链接。我不知道有什么习惯用法,但是random。sample满足您的需要 >>>

是否有一种pythonic方法对序列类型进行切片,以使返回的切片具有随机长度随机顺序?例如,类似于:

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

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

可以找到随机模块文档的快速链接。

我不知道有什么习惯用法,但是
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]

你的问题和其他答案之间有一个微妙的区别,所以我觉得我应该指出这一点。下面的例子说明了这一点

>>> 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
类似于
排序的

+1,了解文字“slice”注释和目的解决方案。@senderle
shuffled=lambda p:sample(p,len(p))