python 进行数据列表按比例随机拆分 random split list
import random # 数据集拆分函数: 将列表 full_list按比例ratio(随机)划分为3个子列表sublist_1、sublist_2、sublist_3 def data_split(full_list, ratio, shuffle=False): n_total = len(full_list) offset0 = int(n_total * ratio[0]) offset1 = int(n_total * ratio[1]) offset2 = int(n_total * ratio[2]) if n_total == 0: # 列表为空的情况 return [] if offset0 + offset1 + offset2 > n_total: # 错误切分条件 print("错误切分比例:因为:", ratio[0], "+", ratio[1], "+", ratio[2], "=", ratio[0] + ratio[1] + ratio[2], ">1") return 0 if offset0 + offset1 + offset2 <= n_total:# 切分 random.shuffle(full_list) sublist_1 = full_list[:offset0] sublist_2 = full_list[offset0:offset0 + offset1] sublist_3 = full_list[offset0 + offset1:] return sublist_1, sublist_2, sublist_3 if __name__ == "__main__": number = int(input("请输入要生成的列表内的随机数个数:")) data = list(range(number)) ratio = [] ratio1, ratio2, ratio3 = eval(input("请输入切分比列,用逗号隔开:")) ratio.append(ratio1) ratio.append(ratio2) ratio.append(ratio3) # print(ratio) sub_data1, sub_data2, sub_data3 = data_split(data, ratio, shuffle=True) print(sub_data1, ",", sub_data2, ",", sub_data3) # 打印结果
正确输入切分比例 结果:
错误输入切分比例 结果:
hello my world
本文来自博客园,作者:slowlydance2me,转载请注明原文链接:https://www.cnblogs.com/slowlydance2me/p/16838841.html