Reputation: 45
I have a list I'd like to split or divide into multiple sub lists. It would be nice for it to be in order but it doesn't have to. I'd like to split it into 3-5 lists if possible. At the moment I'm using the following code but I'd like to know if there's a better way to do it.
data_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print [data_list[i::3] for i in range(3)]
#output => [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9]]
The list will be of random length. Sometimes it can be 2 other times it can be 103 elements (w/ remainders). I know there have been other posts for this but I haven't found a good answer. Was hoping to change that this time around...any tips would be greatly appreciated!
Upvotes: 2
Views: 129
Reputation: 384
Here's a way:
import math
def create_sublist(data_list, num_sublists):
sublist_length = math.ceil(len(data_list)/num_sublists)
list_of_sublists = []
while data_list != []:
sublist = []
for i in range(min(len(data_list), sublist_length)):
sublist.append(data_list.pop(0))
list_of_sublists.append(sublist)
print(list_of_sublists)
create_sublist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 3)
>>> [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j']]
Upvotes: 0
Reputation: 374
Not sure what means a better way for you but still, here's my shot:
import random
def split(data_list):
new_list = []
while len(data_list) != 0:
add = random.randint(3,5)
separed_list = []
for i in xrange(add):
if len(data_list):
separed_list.append(data_list.pop(0))
new_list.append(separed_list)
print(new_list)
split(['a', 'b', 'c', 'd', 'e', 'f', 'j']);
Upvotes: 1