• 从列表中或数组中随机抽取固定数量的元素组成新的数组或列表


    从列表中或数组中随机抽取固定数量的元素组成新的数组或列表

    1:python版本:python里面一行代码就能随机选择3个样本

    >>> import random
    >>> mylist=list(range(1,10))
    >>> mylist
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> newlist = random.sample(mylist, 3)  #从mylist中随机获取3个元素
    >>> newlist
    [4, 7, 2]
    >>> newlist = random.sample(mylist, 3)  #从mylist中随机获取3个元素
    >>> newlist
    [4, 3, 1]
    >>> newlist = random.sample(mylist, 3)  #从mylist中随机获取3个元素
    >>> newlist
    [5, 9, 3]
    >>> 
    

    2:jQuery版本
    那么jQuery中怎么随机选出固定数组数组[1, 2, 3, 4, 5, 6, 7, 8, 9]中的三个元素,并构造成新数组的?

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
        </head>
        <body>
            
        </body>
        <script language="javascript">
    //从一个给定的数组arr中,随机返回num个不重复项
    function getArrayItems(arr, num) {
        //新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
        var temp_array = new Array();
        for (var index in arr) {
            temp_array.push(arr[index]);
        }
        //取出的数值项,保存在此数组
        var return_array = new Array();
        for (var i = 0; i<num; i++) {
            //判断如果数组还有可以取出的元素,以防下标越界
            if (temp_array.length>0) {
                //在数组中产生一个随机索引
                var arrIndex = Math.floor(Math.random()*temp_array.length);
                //将此随机索引的对应的数组元素值复制出来
                return_array[i] = temp_array[arrIndex];
                //然后删掉此索引的数组元素,这时候temp_array变为新的数组
                temp_array.splice(arrIndex, 1);
            } else {
                //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
                break;
            }
        }
        return return_array;
    }
    
    //测试
    var ArrList=[1, 2, 3, 4, 5, 6, 7, 8, 9];
    alert(getArrayItems(ArrList,3));
    </script>
    </html>
    
  • 相关阅读:
    〖Linux〗Kubuntu设置打开应用时就只在打开时的工作区显示
    〖Linux〗Kubuntu, the application 'Google Chrome' has requested to open the wallet 'kdewallet'解决方法
    unity, dll is not allowed to be included or could not be found
    android check box 自定义图片
    unity, ios skin crash
    unity, Collider2D.bounds的一个坑
    unity, ContentSizeFitter立即生效
    类里的通用成员函数应声明为static
    unity, Gizmos.DrawMesh一个坑
    直线切割凹多边形
  • 原文地址:https://www.cnblogs.com/wangting888/p/9701374.html
Copyright © 2020-2023  润新知