-2

I am working on a project in python and I need to split a list of numbers that has a random length into three equal parts. I have simplified code into a basic situation in order to find out the basic way that u can then used for my modular program using objects in the list and queues instead of just numbers. I really dont know how to split it so I just have it set up.

here is the basic code I have

import random 
import Queue
lenth = random.randint(1,15)
l = []

for i in range(lenth):
    im = random.randint(1,20)
    l.append(im)

qOne = Queue.Queue()
qTwo = Queue.Queue()
qThree = Queue.Queue()
Ajay
  • 5,267
  • 2
  • 23
  • 30
compStudent
  • 71
  • 2
  • 7
  • As the list length can vary from 1 to 15, you can't always split the list in three queues with the same length. What is the expected output if the list length is 4 or 7? – Andrea Corbellini May 10 '15 at 16:39
  • possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Andrea Corbellini May 10 '15 at 16:40

1 Answers1

0

Well, if not very pythonic, you could add to the queues as you scan the list with a simple loop. Assuming len(l) % 3 == 0:

len_3rd = len(l)/3
for i,el in enumerate(l):
  if i < len_3rd:
   qOne.put(el)
  elif i>= len_3rd and i<2*len_3rd:
   qTwo.put(el)
  else:
   qThree.put(el)

Or do it with three separate loops, avoiding the ifs.

Pynchia
  • 10,996
  • 5
  • 34
  • 43