python中列表的随机分割

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Time     :  18:33
# Email    : [email protected]
# File     : listSplit.py
__author__ = "ChenLiang.Miao"

# import --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ #
import random
import math
import copy


# function +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ #
def getRandom(num, objList):
    totalNum = len(objList)
    numList = [random.randint(1, 10 * num) for _ in range(num)]
    exDiv = round(1.0 / sum(numList), 7)
    numList = [round(each * exDiv, 7) for each in numList]
    objs = copy.copy(objList)

    for each in numList:
        yield _get_split_(objs, each, totalNum)
    pass


def _get_split_(objList, num, totalNum):
    pick = int(math.ceil(num * totalNum))
    if pick >= objList.__len__():
        return objList
    val = random.sample(objList, pick)
    for each in val:
        objList.remove(each)
    return val


# +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ #
if __name__ == '__main__':
    for each in getRandom(5, range(60)):
        print each

注意事项:

对于计算机来说,除法计算一般都比较复杂,所有我们先计算一次除法,然后在代码中使用乘法。

python中标签的定义,相当于内存的划分,所以类似这种生产后马上就要被修改的,最好使用相同的名称。

 

numList = [random.randint(1, 10 * num) for _ in range(num)]
exDiv = round(1.0 / sum(numList), 7)
numList = [round(each * exDiv, 7) for each in numList]

 

你可能感兴趣的:(python中列表的随机分割)