Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.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 - Fatal编程技术网

Python 如果随机样本量太大,请选择整个列表

Python 如果随机样本量太大,请选择整个列表,python,Python,在Python中,我们可以从列表中随机抽样,如下所示: >>> import random >>> l = [1,2,3] >>> random.sample(l,2) [2, 3] 但是,如果样本大小大于列表,则返回错误: >>> random.sample(l,4) Traceback (most recent call last): File "<stdin>", line 1, in <mod

在Python中,我们可以从列表中随机抽样,如下所示:

>>> import random
>>> l = [1,2,3]
>>> random.sample(l,2)
[2, 3]
但是,如果样本大小大于列表,则返回错误:

>>> random.sample(l,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 315, in sample
    raise ValueError("Sample larger than population")
ValueError: Sample larger than population
>随机样本(l,4)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/local/ceral/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py”,第315行,在示例中
提升值错误(“样本大于总体”)
ValueError:样本大于总体
如果样本量大于列表,是否有允许
random.sample
选择整个列表的选项?

没有此类选项(请参见
帮助(random.sample)
),但您始终可以控制传递的内容:

random.sample(l, min(len(l),4))
没有此类选项(请参见
帮助(random.sample)
),但您始终可以控制传递的内容:

random.sample(l, min(len(l),4))
比如:

random.sample(l) if len(l)<4 else random.sample(l, 4)
random.sample(l)如果len(l)类似于:

random.sample(l) if len(l)<4 else random.sample(l, 4)

random.sample(l)if len(l)
random(l,…)
也会重新排列列表,但您的表达式不会。不需要重新排列,但可以轻松实现-更新。
random(l,…)
也会重新排列列表,但是你的表情没有。没有洗牌的要求,但它可以很容易地实现-更新。这很有意义。谢谢这很有道理。谢谢