繁体   English   中英

Python从输入列表中输出随机列表

[英]Python output random lists from input list

我需要从我的 list1 中创建 3 个列表。 一个具有 70% 的值,两个具有 20% 和 10% 的值。

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# listOutput70 = select  70% of list1 items(randomly)
# with the remaining create two lists of 20% and 10%

#the output can be something like:

#listOutput70 = [2,7,9,8,4,10,3]
#listOutput20 = [1,5]
#listOutput10 = [6]

我已经有一些代码来生成百分比输出,但仅适用于一个列表。

import random


def selector():

    RandomSelection = []
    mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    PercentEnter= 70
    
    New_sel_nb = len(mySel)*int(PercentEnter)/100
        
    
    while len(RandomSelection) < New_sel_nb:
        randomNumber = random.randrange(0, len(mySel),1)
    
        RandomSelection.append(mySel[randomNumber])
    
        RandomSelection = list(set(RandomSelection))
        
    print(RandomSelection)


selector()
#[2, 3, 6, 7, 8, 9, 10]

使用random.shuffle()随机播放列表。 然后使用切片来获得每个百分比。

def selector(percents):
    RandomSelection = []
    mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    random.shuffle(mySel)
    
    start = 0
    for cur in percents:
        end = start + cur * len(mySel) // 100
        RandomSelection.append(mySel[start:end])
        start = end

    return RandomSelection

print(selector([70, 20, 10]))

使用numpy.split函数:

from random import shuffle
from numpy import split as np_split


def selector(og_list, percentages):
    if sum(percentages) != 100:
        raise ValueError("Percentages must sum to 100!")
    percentages.sort()
    splits = [round(len(og_list) * percentages[0] / 100),
              round(len(og_list) * (percentages[0] + percentages[1]) / 100)]
    shuffle(og_list)
    return [list(subset) for subset in np_split(og_list, splits)]

用法:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

my_percentages_1 = [10, 20, 70]
my_percentages_2 = [40, 10, 50]
my_percentages_3 = [63, 31, 6]

result_1 = selector(my_list, my_percentages_1)
result_2 = selector(my_list, my_percentages_2)
result_3 = selector(my_list, my_percentages_3)

print(result_1)
print(result_2)
print(result_3)
[[2], [8, 3], [4, 9, 7, 5, 0, 1, 6]]
[[8], [0, 2, 7, 1], [9, 4, 6, 3, 5]]
[[1], [0, 3, 2], [4, 8, 5, 9, 7, 6]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM