-3

I'm new to Python, I have a list that consists of a lot of numbers like:

 list=[1,2,3,4,5,6,7,...]

I need to divide it into three parts, to make the first part contain the earliest 1/3 numbers, and the second part contain the second 1/3 numbers, and the last part consist of the last 1/3 numbers, for example:

part1=[1,2,3,4..."the len(list)/3 th number"], 
part2=[" the len(list)/3+1 th number, ... , 
2*len(list)/3 th number]

Could you help me figure out how to do it?

Serenity
  • 35,289
  • 20
  • 120
  • 115
Weaver
  • 11
  • 1
  • 1
    What do you need help with exactly? It looks like you've given us your assignment pretty much in full. We can answer questions you have but we're not going to flat out do your homework for you. – John Kugelman Apr 22 '15 at 03:12
  • If the position of the items in the list is sorted already, you can refer to different pieces like so: `list[0:2]` ... But I'm not really sure what you're asking. – tandy Apr 22 '15 at 03:19
  • @JohnKugelman Apparently some people *will* flat out do his/her homework for him/her. – Shashank Apr 22 '15 at 03:30
  • 1
    possible duplicate of [Split list into smaller lists](http://stackoverflow.com/questions/752308/split-list-into-smaller-lists) – Zaaferani Apr 22 '15 at 03:47
  • That's not my homework... I'm in a class called mobile robot, learning something called ROS and my professor recommend to use python... my homework is get the out put from a lasersensor and decide where is the obstacle and whether I should turn left or right... I thought to divide the data into right front and left list, and find out where the obstacle is by comparing the average of the three lists... but since I'm not familiar with python, I just want to make sure that I'm not making mistakes... – Weaver Apr 22 '15 at 04:08

2 Answers2

2
l = [1,2,3,4,56,789,1,3,4,5,6,1,213,4]
_s = (len(l) / 3) + 1
print l[:_s], l[_s:2*_s], l[2*_s:]

[1, 2, 3, 4, 56] [789, 1, 3, 4, 5] [6, 1, 213, 4]
Zaaferani
  • 951
  • 9
  • 31
0

Maybe this func can help you.

def list_split(src_list, length):
    """
    Split list to small lists
    -------------
    Parameter
    length :  length of small list
    """
    for i in xrange(0, len(src_list), length):
        yield src_list[i:i + length]
linhao.Q
  • 71
  • 1
  • 3
  • This solution certainly works when the length is divisible by 3, but it could be better for other lengths. It is particularly problematic for a list of length 4, since that will either generate 2 lists of 2 or 4 lists of 1, but will not generate 3 lists. – Brad Budlong Apr 22 '15 at 03:27