Splitting List In Python
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. A
Solution 1:
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']);
Solution 2:
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']]
Post a Comment for "Splitting List In Python"