473,327 Members | 2,094 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Simple List division problem

How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ?
consider this example:

x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x
what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

obviously not even, one list will have 4 elements, the other 2 will
have 3.,
the overriding logic, is that I will get 3 lists and find a way for
python to try to break it evenly, if not one list can have a greater
amount of elements

Would I use itertools ? How would I do this ?

Thanks
Jan 12 '08 #1
10 1395
marcstuart wrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ?
consider this example:

x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x
what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

obviously not even, one list will have 4 elements, the other 2 will
have 3.,
the overriding logic, is that I will get 3 lists and find a way for
python to try to break it evenly, if not one list can have a greater
amount of elements

Would I use itertools ? How would I do this ?

Thanks
Calculate the size of a normal sublist, and the amount of extra that
goes with the last sublist.
Then extract y-1 normal sized sublists and one possibly larger sublist.
>>x = [1,2,3,4,5,6,7,8,9,10]
y = 3
s = len(x)/y
s # size of normal sublists
3
>>e = len(x) - y*s # extra elements for last sublist
e
1
>>z = [x[s*i:s*i+s] for i in range(y-1)] + [x[-s-e:]] #extract y-1
normal + 1 larger sublists
>>z
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

Done!

Gary Herron

Jan 12 '08 #2
marcstuart wrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ? consider this example:

x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x

what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

obviously not even, one list will have 4 elements, the other 2 will
have 3.,
here's one way to do it:

# chop it up
n = len(x) / y
z = [x[i:i+n] for i in xrange(0, len(x), n)]

# if the last piece is too short, add it to one before it
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))

</F>

Jan 12 '08 #3
On Jan 12, 12:37*pm, marcstuart <marc.stuart.ris...@gmail.comwrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ?
consider this example:

x = [1,2,3,4,5,6,7,8,9,10]
y = 3 * * *# number of lists I want to break x into
z = y/x

what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

obviously not even, one list will have 4 elements, the other 2 will
have 3.,
the overriding logic, is that I will get 3 lists and find a way for
python to try to break it evenly, if not one list can have a greater
amount of elements

Would I use itertools ? How would I do this ?

Thanks
def list_split(x,y):
dm = divmod(len(x),y)
if dm[1] != 0:
z = [x[i*y:i*y+y] for i in xrange(len(x)/y) if len(x[i*y:])>=2*y]
z.append(x[(len(x)/y-1)*y:])
else:
z = [x[i*y:i*y+y] for i in xrange(len(x)/y)]
return z
>>list_split([1,2,3,4,5,6,7,8,9,10],3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>list_split([1,2,3,4,5,6,7,8,9,10],5)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
>>list_split([1,2,3,4,5,6,7,8,9,10],4)
[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10]]
>>list_split([1,2,3,4,5,6,7,8,9,10],2)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
Jan 12 '08 #4
marcstuart <ma****************@gmail.comwrites:
what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]
Are you SURE you want that? In almost every situation I've seen,

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9]
print z[4] = [10]

is preferable.
Jan 12 '08 #5
On Jan 12, 2:25 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
marcstuart <marc.stuart.ris...@gmail.comwrites:
what I would like to get is 3 sublists
print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

Are you SURE you want that? In almost every situation I've seen,

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9]
print z[4] = [10]

is preferable.
Even more preferable is:

print z[0] = [1,2,3]
print z[1] = [4,5,6]
print z[2] = [7,8,9]
print z[3] = [10]
Jan 12 '08 #6
On Jan 12, 8:33 pm, Fredrik Lundh <fred...@pythonware.comwrote:
marcstuart wrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ? consider this example:
x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x
what I would like to get is 3 sublists
print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]
obviously not even, one list will have 4 elements, the other 2 will
have 3.,

here's one way to do it:

# chop it up
n = len(x) / y
z = [x[i:i+n] for i in xrange(0, len(x), n)]

# if the last piece is too short, add it to one before it
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))

</F>
Eh...

def chop(lst, length):
n = len(lst) / length
z = [lst[i:i+n] for i in xrange(0, len(lst), n)]
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))
return z

gives
>>chop(range(1,9), 3)
[[1, 2], [3, 4], [5, 6], [7, 8]]
>>chop(range(1,8), 3)
[[1, 2], [3, 4], [5, 6, 7]]
>>chop(range(1,6), 3)
[[1], [2], [3], [4], [5]]
>>chop([1], 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "beforemeth.py", line 9, in chop
if len(z[-1]) < n and len(z) 1:
ValueError: xrange() arg 3 must not be zero

Perhaps something like this?

def chop(lst, length):
from itertools import islice
it = iter(lst)
z =[list(islice(it, length)) for i in xrange(1 + len(lst) //
length)]
if len(z) 1:
z[-2].extend(z.pop()) # the last item will be empty or contain
"overflow" elements.
return z

-- bjorn
Jan 13 '08 #7
On Jan 13, 1:05 pm, thebjorn <BjornSteinarFjeldPetter...@gmail.com>
wrote:
On Jan 12, 8:33 pm, Fredrik Lundh <fred...@pythonware.comwrote:
marcstuart wrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ? consider this example:
x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x
what I would like to get is 3 sublists
print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]
obviously not even, one list will have 4 elements, the other 2 will
have 3.,
here's one way to do it:
# chop it up
n = len(x) / y
z = [x[i:i+n] for i in xrange(0, len(x), n)]
# if the last piece is too short, add it to one before it
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))
</F>

Eh...

def chop(lst, length):
n = len(lst) / length
z = [lst[i:i+n] for i in xrange(0, len(lst), n)]
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))
return z

gives
>chop(range(1,9), 3)

[[1, 2], [3, 4], [5, 6], [7, 8]]>>chop(range(1,8), 3)

[[1, 2], [3, 4], [5, 6, 7]]>>chop(range(1,6), 3)

[[1], [2], [3], [4], [5]]>>chop([1], 3)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "beforemeth.py", line 9, in chop
if len(z[-1]) < n and len(z) 1:
ValueError: xrange() arg 3 must not be zero

Perhaps something like this?

def chop(lst, length):
from itertools import islice
it = iter(lst)
z =[list(islice(it, length)) for i in xrange(1 + len(lst) //
length)]
if len(z) 1:
z[-2].extend(z.pop()) # the last item will be empty or contain
"overflow" elements.
return z

-- bjorn
Bad for to reply to myself, I know, but I just realized that the OP
wanted to control the _number_ of chunks, not the size of the
chunks... Building on the above would give something like

from itertools import islice
from operator import add

def chop(lst, nchunks):
chunksize, extra = divmod(len(lst), nchunks)
if not chunksize:
raise ValueError('More chunks than elements in list.')
it = iter(lst)
z =[list(islice(it, chunksize)) for i in xrange(nchunks + extra)]
z, extra = z[:nchunks], z[nchunks:]
z[-1].extend(reduce(add, extra, [])) # because sum ain't add :-(
return z

-- bjorn
Jan 13 '08 #8
thebjorn wrote:
Eh...
oh, forgot that it was "pulling requirements out of thin air" week on
c.l.python.
def chop(lst, length):
n = len(lst) / length
z = [lst[i:i+n] for i in xrange(0, len(lst), n)]
if len(z[-1]) < n and len(z) 1:
z[-2].extend(z.pop(-1))
return z

gives
>>>chop([1], 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "beforemeth.py", line 9, in chop
if len(z[-1]) < n and len(z) 1:
ValueError: xrange() arg 3 must not be zero
well, it doesn't. there's no xrange on that line.
Perhaps something like this?
from itertools import islice
or just use an if-statement, or the max function. but I guess those
tools are too old and boring for c.l.python these days...

</F>

Jan 13 '08 #9
thebjorn <Bj************************@gmail.comwrites:
Perhaps something like this?

def chop(lst, length):
from itertools import islice
it = iter(lst)
z =[list(islice(it, length)) for i in xrange(1 + len(lst) // length)]
if len(z) 1:
z[-2].extend(z.pop()) # the last item will be empty or contain "overflow" elements.
return z
def chop(lst, length):
def chop1():
t = len(lst) // length - 1
for i in xrange(t):
yield lst[i*length: (i+1)*length]
yield lst[t*length:]
return list(chop1())
Jan 13 '08 #10
On 12 jan, 19:37, marcstuart <marc.stuart.ris...@gmail.comwrote:
How do I divide a list into a set group of sublist's- if the list is
not evenly dividable ?
consider this example:

x = [1,2,3,4,5,6,7,8,9,10]
y = 3 # number of lists I want to break x into
z = y/x

what I would like to get is 3 sublists

print z[0] = [1,2,3]
print z[2] = [4,5,6]
print z[3] = [7,8,9,10]

obviously not even, one list will have 4 elements, the other 2 will
have 3.,
the overriding logic, is that I will get 3 lists and find a way for
python to try to break it evenly, if not one list can have a greater
amount of elements

Would I use itertools ? How would I do this ?

Thanks
Hi,

If you want to split the list in 4, do you want
[1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist
or
[1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last
sublists ?

Assuming you want the second version :

=======================
def split_list(lst,nb):
# ln = length of smaller sublists
# extra = number of longer sublists (they have ln+1 items)
ln,extra = divmod(len(lst),nb)
pos = ln*(nb-extra) # position where larger sublists begin
return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \
+ [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)]

======================

x = range(1,11)

print split_list(x,1)
>>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
print split_list(x,2)
>>>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
print split_list(x,3)
>>>[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print split_list(x,4)
>>>[[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]]
print split_list(x,5)
>>>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
print split_list(x,10)
>>>[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
Jan 14 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: marx | last post by:
I have a bit of a problem and any help would be much appreciated. Problem: I have two dropdown list boxes with same data(all data driven). These are used for two separate entries. For every...
2
by: Kathy | last post by:
Scenario: Multiple Divisions. Each Division has multiple Buildings. Each Building has multiple Floors. Each Floor has a Supervisor. Tables: (abbreviated) TblDivision DivisionID Division
5
by: Yodai | last post by:
Hi all! I have an int that comes with a value like 0x07fa and I have to turn it into a float value of 204.2 decimal to display it.... if I try to divide it by 10 I get bogus numbers. I presume...
13
by: RadiationX | last post by:
I have to solve the following problem:Write a program that accepts two integers, and determines if the second is a factor (is evenly divisible into) the first. Here is the code i have so far. ...
1
by: Synapse | last post by:
Hello... We were asked to create a simple calculator program in our C++ subject by using loops only. i have a problem in creating a loop in the multiplication and division operation so please can...
0
VbaNewbee
by: VbaNewbee | last post by:
I have a form with a few filters. Once the user clicks "search button", the code first evaluates my filters, then shows the query results in a List Box" titled backschedule. I have a few text...
1
Death Slaught
by: Death Slaught | last post by:
I will be showing you how to make a very simple but effective three column layout. First we will begin with the HTML, or structure, of our three column layout. <!DOCTYPE html PUBLIC...
0
by: sharontompkins | last post by:
I am trying to pull up records that are linked from two separate tables. The fields in play and their characteristics are listed below. Two table are being utilized, Registrations (Name, Reg #,...
1
by: rh0dium | last post by:
Hi all, Perhaps it's not supposed to work like this but I thought if you supplied a width to pprint it would nicely format a list to the width. KEYS = pp = pprint.PrettyPrinter(indent=2)...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.