python - 列表均匀分片示例代码
程序员文章站
2024-03-19 22:35:58
...
列表均匀分片示例代码:
"""
@author: zhangjun.xue
@time: 2020/6/30 16:32
@file: split_data_util.py
@desc: 对数据进行分片
"""
import traceback
def split_data(split_num, orgin_data):
"""
:param split_num: 设置分片数
:param orgin_data: 要分片的原始数据
:return:
"""
try:
spli_data = []
count = 0
while count < split_num:
spli_data.append([])
count += 1
for data in orgin_data:
spli_data[orgin_data.index(data) % split_num].append(data)
return spli_data
except:
raise Exception(traceback.format_exc())
if __name__ == "__main__":
pass
test_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
# 分3片
print(split_data(3, test_list))
# 分5片
print(split_data(5, test_list))
# split_num = 0
# split_count = 3
# my_data_list_0 = []
#
# for index, data in enumerate(test_list):
# print('data = {} , index = {}'.format(data, index))
# if index % split_count == split_num:
# my_data_list_0.append(data)
# print('my_data_list_0 = ', my_data_list_0)
#
# split_num = 1
# my_data_list_1 = []
# for index, data in enumerate(test_list):
# # print('data = {} , index = {}'.format(data, index))
# if index % split_count == split_num:
# my_data_list_1.append(data)
# print('my_data_list_1 = ', my_data_list_1)
#
# split_num = 2
# my_data_list_2 = []
# for index, data in enumerate(test_list):
# # print('data = {} , index = {}'.format(data, index))
# if index % split_count == split_num:
# my_data_list_2.append(data)
# print('my_data_list_2 = ', my_data_list_2)
输出:
[['a', 'd', 'g', 'j'], ['b', 'e', 'h', 'k'], ['c', 'f', 'i']]
[['a', 'f', 'k'], ['b', 'g'], ['c', 'h'], ['d', 'i'], ['e', 'j']]